On pg 185/186 of CLR Via C# 4th Edition, it has this code example:
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
}
}
internal struct Point
{
public Int32 m_x, m_y;
public Point()
{
m_x = m_y = 5;
}
}
internal sealed class Rectangle
{
public Point m_topLeft, m_bottomRight;
public Rectangle()
{
}
}
This won't compile because you can't define a parameterless constructor for a struct.
Jeff goes on to say:
C# purposely disallows value types from defining parameterless constructors to remove any confusion a developer might have about when that constructor gets called.
However if you replace struct
with class
, the code compiles, and when run, the Point
constructor doesn't get called, which could be unexpected for people new to programming.
EDIT: Maybe I've understood it incorrectly, but I think Jeff is trying to say that some people may think that if value types were to have a parameterless constructor, it would be called for every instance in Point array = new Point[100];
, which is not what would happen. If so, then you've got the same potential confusion with reference types right?
I know Jon Skeet wrote an answer here, however all those points could also be applied to reference types, yet reference types ARE allowed parameterless constructors.