views:

291

answers:

4

Consider this code block:

    struct Animal
    {
        public string name = ""; // Error 
        public static int weight = 20; // OK

        // initialize the non-static field here 
        public void FuncToInitializeName()
        {
         name = ""; // Now correct
        }
    }
  • Why can we initialize a static field inside a struct but not a non-static field?
  • Why we have initialize non-staticin methods bodies?
A: 

A struct is not an actual object, but is a declaration of a type of object. At least, that's how it is in C-regular.

amphetamachine
but why only static field could be initialized ?
Asad Butt
A: 

You cannot write a custom default constructor in a structure. The instance field initializers will eventually need to get moved to the constructor which you can't define.

Static field initializers are moved to a static constructor. You can write a custom static constructor in a struct.

Mehrdad Afshari
+8  A: 

Have a look at Why Can't Value Types have Default Constructors?

astander
Although at the IL level they can: http://msmvps.com/blogs/jon_skeet/archive/2008/12/10/value-types-and-parameterless-constructors.aspx
Jon Skeet
A: 

You can do exactly what you're trying. All you're missing is a custom constructor that calls the default constructor:

struct Animal
{
    public string name = ""; 
    public static int weight = 20; 

    public Animal(bool someArg) : this() { }
}

The constructor has to take at least one parameter, and then it has to forward to this() to get the members initialised.

The reason this works is that the compiler now has a way to discover the times when the code should run to initialise the name field: whenever you write new Animal(someBool).

With any struct you can say new Animal(), but "blank" animals can be created implicitly in many circumstances in the workings of the CLR, and there isn't a way to ensure custom code gets run every time that happens.

Daniel Earwicker