Why can't non-static fields be initialized inside structs?

Viewed 4311

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 do we have to initialize non-static in methods bodies?
4 Answers

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.

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.

Related