Another reason is that structs don't have inheritance and are allocated on
the stack (until they're boxed at which time they get copied onto the heap).
When they're on the stack, they can really be though of as just a grouping
of nested locals on the stack. Until you box them or pass them to some
other method the compiler treats them as such and allows each member to be
independently initialized and used accordingly. This allows methods to
dynamically initialize certain members based on calculated information,
rather than requiring heavy handed stuff like forcing you to zero initialize
everything and then overwrite that with the real value later (plus it
prevents you from accessing the member before the 'real value' has been
set). Now when you pass that struct to some other method or cause it to be
boxed, the method being called has the implicit contract that input
parameters are fully initialized, and so at that point the compiler requires
that all members have been initialized. A similar statement is true for
boxing.
--
--Grant
This posting is provided "AS IS" with no warranties, and confers no rights.
"emma middlebrook" <em**************@fastmail.fm> wrote in message
news:e2**************************@posting.google.c om...
Hi
I discovered that if you declare a structure (and not 'new()' it) you
can then separately initialize its members and the compiler counts
those separate statements as a full initialization. That struck me as
a bit odd really as I would have thought it would have only bothered
about 'tracking' an 'atomic'/'complete' (via 'new()') initialization
not doing it 'bit by it'!!! Any comments? Seems a bit of an overhead
tracking memberwise initialization doesn't it? Any C# compiler people
out there?
Hoping for some comments to show me that this isn't such a weird thing
please.
Emma Middlebrook
em**************@fastmail.fm
struct Value
{
public int x;
public int y;
}
Value v2;
v2.x = 6; // v2 can not be used yet as 'unassigned' ...
v2.y = 7; // v2 can now be used as all its parts are initialized.