By clicking on a few small structures while replying to this post , I unexpectedly discovered the following:
The following structure using the int field is completely legal:
struct MyStruct { public MyStruct ( int size ) { this.Size = size;
However, the following structure using an automatic property does not compile:
struct MyStruct { public MyStruct ( int size ) { this.Size = size;
Error returned: "Object 'this' cannot be used before all its fields have been assigned." I know that this is the standard procedure for struct: the support field for any property must be assigned directly (and not through the accessory of the property set) from the constru constructor.
The solution is to use an explicit support field:
struct MyStruct { public MyStruct(int size) { _size = size; } private int _size; public int Size { get { return _size; } set { _size = value; } } }
(Note that VB.NET will not have this problem because in VB.NET all fields are automatically initialized to 0 / null / false on first creation.)
This may seem like an unfortunate limitation when using automatic properties using C # structures. Thinking conceptually, I was wondering if this would be a reasonable place for an exception that allows the calling attribute of a property to be assigned in the structure constructor, at least for an automatic property?
This is a minor issue, almost extreme, but I was wondering what others thought about it ...
Mike Rosenblum Jan 07 '09 at 14:14 2009-01-07 14:14
source share