C# does not allow a struct to declare a default, no-parameters, constructor. The reason for this constraint is to do with the fact that, unlike in C++, a C# struct is associated with value-type semantic and a value-type is not required to have a constructor. CLR (not C#) allows a value-type to have a default constructor but it is not guaranteed to be always called. To avoid the ambiguity of whether the default constructor of a value-type would be called or not C# compiler does not insert a call to a value-type default constructor, and that precludes the definition of one.
A C# struct cannot have a default constructor, but it can declare a constructor that has parameters. What if all the parameters of a constructor have a default value, would that be considered a default constructor or not? Consider this code and answer the question that follows it.
struct Rectangle {
public int length;
public int width;
// A constructor with all default parameters.
public Rectangle(int l = 1, int w = 1) {
length = l;
width = w;
}
public int Perimeter() {
return 2*length + 2*width;
}
}
class Program
{
static void Main() {
Rectangle rectangle = new Rectangle();
Console.WriteLine("{0}", rectangle.Perimeter());
}
}
What do you think is the perimeter of rectangle in above code?