views:

236

answers:

3

Inside XNA struct Vector2 are two public variables X and Y. I have the following code:

Vector2 v; if(b) v.X=1; else v.Y=2;

//use v

The compiler gives "Use of unassigned local variable 'v'" But it runs correctly nonetheless.

Is there a more correct way of doing it?

+4  A: 

C# requires you assign a value to your local variables before you use them.

Vector2 v = new Vector2();
280Z28
+2  A: 

It works because a struct is automatically initialized. All of its members are set to their Type's default value. But if you use an unassigned variable like this, it's usually because you forgot to assign it before. I guess the compiler doesn't make a difference between structs and classes here.

Botz3000
A: 

Imho, this is a very bad idea. Structs in C# are value-types. C# imposes a number of restrictions to ensure that all fields of a struct are initialized:

  • Default constructors are not allowed.
  • Constructors must initialize all fields within the struct.

If you do not instantiate a struct through a constructor, then all members are set to the result of calling default() on the member type. This allows structs to be used in arrays. It also allows what you are doing, but is also the reason for the warning.

Ideally, you should define a constructor and initialize the struct with the constructor.

Edit: To clarify the restriction on the default (parameterless) constructor, you cannot explicitly define one, because the compiler provides one, which it uses to initializes all members.

nagul