Are uninitialized members of the structure guaranteed to have value?

If you use the initialization list to create a struct , do the members you exit get the known default value?

 public struct Testing { public int i; public double d; public string s; } Testing test = new Testing { s="hello" }; 

I found a link at Microsoft that implies this, but doesn’t indicate it explicitly: Default table (C # link) .

A small test program shows that it does not generate a compiler error and does not produce the expected results. I know better than relying on simple warranty tests. http://ideone.com/nqFBIZ

+6
source share
2 answers

Yes, they contain the default value (T), where T is the type of value. Links to objects will be empty.

Excerpts:

As described in section 5.2, several kinds of variables are automatically initialized by default when they are created. For variable class types and other reference types, this Default value is null. However, since structures are types of values ​​that cannot be null, the default value for struct is the value created by setting all fields of the value type to their default value and enter fields of type null for the entire link.

Taken from here:

http://msdn.microsoft.com/en-us/library/aa664475(v=vs.71).aspx

I remember when I studied MOC for certification that they explicitly state this. This is a guaranteed language feature.

+9
source

To expand the pid answer:

 test = new Testing { s = hello } 

listed as having semantics:

 Testing temp = new Testing(); temp.s = "hello"; test = temp; 

The default constructor of a value type is documented as a constructor that sets all instance fields to default values.

In a more general sense, C # requires that any value type constructor have a property, so that all fields are necessarily assigned before the constructor completes normally.

Now, if the constructor is not called, then there are two cases. If the variable was originally assigned, the variable acts as if the default constructor were called. For example, if you say

 Testing[] test = new Testing[1]; 

Then test[0] initialized to the default value just as if you said

 Testing[] test = new Testing[1] { new Testing() }; 

If a variable is not initially assigned, for example, a local variable, you must necessarily assign all the fields before reading them. That is, if we have local:

 Testing test; test.s = "hello"; Console.WriteLine(test.d); // ERROR, test.d has not been written yet. 

Note also that volatile structures are the worst practice in C #. Instead, create a public constructor that defines all the fields, make the fields private, and put getters properties in them.

+6
source

All Articles