Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Structs: Unassigned local variable?

Tags:

c#

struct

From the documentation:

Unlike classes, structs can be instantiated without using a new operator.

So why am I getting this error:

Use of unassigned local variable 'x'

When I try to do this?

        Vec2 x;         x.X = det * (a22 * b.X - a12 * b.Y);         x.Y = det * (a11 * b.Y - a21 * b.X); 

Where Vec2 x is a struct?

like image 425
mpen Avatar asked Jan 15 '10 04:01

mpen


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What do you mean by C?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C language w3schools?

C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

Well, are X and Y properties (rather than fields)? If so, that's the problem. Until all the fields within x are definitely assigned, you can't call any methods or properties.

For instance:

public struct Foo {     public int x;     public int X { get { return x; } set { x = value; } } }  class Program {     static void Main(string[] args)     {         Foo a;         a.x = 10; // Valid          Foo b;         b.X = 10; // Invalid     } } 

Is Vec2 your own type? Do you have access to the fields involved, or only the properties?

If it's your own type, I would strongly urge you to try to stick to immutable structs. I know managed DirectX has some mutable structs for getting as close to optimal performance as possible, but that's at the cost of strange situations like this - and much worse, to be honest.

I would personally give the struct a constructor taking X and Y:

 Vec2 x = new Vec2(det * (a22 * b.X - a12 * b.Y),                    det * (a11 * b.Y - a21 * b.X)); 
like image 102
Jon Skeet Avatar answered Oct 19 '22 13:10

Jon Skeet