Domanda

If you use an initializer list to create a struct, do the members you leave out get a 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 it but does not state so explicitly: Default Values Table (C# Reference).

A small test program shows that it does not generate a compiler error and produces the expected results. I know better than to rely on simple tests for guarantees though. http://ideone.com/nqFBIZ

È stato utile?

Soluzione

Yes, they contain default(T) where T is the type of the value. Object references will be null.

Excerpt:

As described in Section 5.2, several kinds of variables are automatically initialized to their default value when they are created. For variables of class types and other reference types, this default value is null. However, since structs are value types that cannot be null, the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null.

Taken from here:

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

I remember when studying the MOC for the certification that they explicitly state this. It is a guaranteed feature of the language.

Altri suggerimenti

To expand on pid's answer:

test = new Testing { s = hello }

is specified as having the semantics of:

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

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

More generally, the C# language requires that any constructor of a value type have the property that all fields be definitely assigned before the constructor terminates normally.

Now, if no constructor is called then there are two cases. If the variable is initially assigned then the variable acts the same as though the default constructor was called. For example, if you say

Testing[] test = new Testing[1];

Then test[0] is initialized to the default value the same as if you'd said

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

If the variable is not initially assigned, for example, a local variable, then you are required to definitely assign all the fields before you read them. That is, if we have a local:

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

Note also that mutable structs are a worst practice in C#. Instead, make a public constructor that sets all the fields, make the fields private, and put property getters on top of them.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top