#643 – The Constructor for a struct Must Initialize All Data Members

.NET requires that you initialize all memory for an object before you use it.  When it comes to a struct, this means that you must do one of three things when declaring a new instance of a struct:

  • Invoke the default parameterless constructor, which initializes all elements within the struct.  (E.g. zeroes out simple value types)
  • Declare the new instance and then set data members explicitly (assuming that they are all public)
  • Invoke a custom constructor, which initializes all data members

This means that if you define a non-default constructor for a struct, your constructor must initialize all data members in the struct before it returns. to the caller.  This guarantees that any creation of a struct-based value type will result in an object which is safe to use, because all of its data members have known values.

Advertisements