Saturday, July 16, 2011

Structs in C#

Just read a very good discussion on structs in Professional C# 4.0 and .NET 4 (Wrox Programmer to Programmer).

Here are the main points:
  • structs are value types, so they get created and destroyed very fast.
  • They are well suited for grouping together a small number of value fields, such as a pair of ints for X,Y coordinates.
  • Because they are values, they do not need to be initialized with the new keyword.   
  • You cannot override the default constructor, nor initialize fields inside a struct, except in a non-default constructor.
  • If you create an instance of the new struct with new, the fields are initialized to their default values.  If you create the struct without new, you must manually initialized the fields before using them.
Poking around with this some more, I've noticed that creating a non-default constructor does not hide the default constructor, unlike classes.