Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 403
Asad Avatar asked Feb 21 '10 06:02

Asad


2 Answers

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

like image 144
Adriaan Stander Avatar answered Nov 17 '22 17:11

Adriaan Stander


The CLI expects to be able to allocate and create new instances of any value type that would require 'n' bytes of memory, by simply allocating 'n' bytes and filling them with zero. There's no reason the CLI "couldn't" provide a means of specifying either that before any entity containing structs is made available to outside code, a constructor must be run on every struct therein, or that a whenever an instance of a particular n-byte struct is created, the compiler should copy a 'template instance'. As it is, however, the CLI doesn't allow such a thing. Consequently, there's no reason for a compiler to pretend it has a means of assuring that structs will be initialized to anything other than the memory-filled-with-zeroes default.

like image 26
supercat Avatar answered Nov 17 '22 18:11

supercat