Search code examples
c#.netstructinstantiation

Why is it possible to instantiate a struct without the new keyword?


Why are we not forced to instantiate a struct, like when using a class?


Solution

  • The why is simply - because the spec says so. The how is a matter of ensuring that the entire block of memory is "definitely assigned", which means: assigning a value to each field of the struct. However, this requires 2 nasty things:

    • public fields (almost always bad)
    • mutable fields (generally bad in a struct)

    so in most best-practice cases, you do need to use the new(...) syntax, to invoke the constructor (or to zero-the memory, for the parameterless constructor) for the type correctly.