I have some code to initialize a struct in C#:
namespace Practice
{
public struct Point
{
public int _x;
public int _y;
public int X
{
get { return _x; }
set { _x = value; }
}
public int Y
{
get { return _y; }
set { _y = value; }
}
public Point(int x, int y)
{
_x = x;
_y = y;
}
}
class Practice
{
public static void Main()
{
Point p1;
p1.X = 1;
p1.Y = 2;
}
}
}
The above code gives a compiler error:
error CS0165: Use of unassigned local variable 'p1'
Why is this error being thrown?
You can't use a property in a struct until it knows all the fields have been filled in.
For example, in your case this should compile:
Point p1;
p1._x = 1;
p1._y = 2;
int x = p1.X; // This is okay, now the fields have been assigned
Note how you don't have to explicitly call a constructor here... although in well-encapsulated structs you almost always would have to. The only reason you can get away with this is because your fields are public. Ick.
However, I would strongly advise you not to use a mutable struct anyway. If you really want a struct, make it immutable and pass the values into the constructor:
public struct Point
{
private readonly int x;
public int X { get { return x; } }
private readonly int y;
public int Y { get { return y; } }
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
...
Point p1 = new Point(1, 2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With