Consider this struct
struct Point
{
int x;
public int X
{
get{ return x; }
set{ x = value; }
}
int y;
public int Y
{
get{ return y; }
set{ y = value; }
}
}
now lets use it in some code
Point p = new Point();
p.X = 10;
p.Y = 20;
this works as the ctor initializes the stucts memory to 0.
However if we change the code to:
Point p;
p.X = 10;
p.Y = 20;
This won't compile as the memory has not been initialized and the property sets are actually method calls.
The only way to make code like that work is to have the fields as public then you can write
Point p = new Point();
p.x = 10;
p.y = 20;
which is allowed. Until you have initialized every field of the struct you cannot call a method on it. You can do this initialization manually or via a constructor. Jesse is saying that you cannot perform this initialization via property sets as they are in fact method calls
Regards
Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog http://www.dotnetconsult.co.uk
Hi,
can someone explain the following extract from Jess Liberty's C# book
(very end of chapter on structs)?
"Be careful about using properties. Although these allow you to
support encapsulation by making the actual values private, the
properties themselves are actually member methods and you cannot call
a member method until you initialize all the member variables". I
don't understand what he means.
Cheers,
Emmanuel