Reputation: 3519
Default parameters must be a compile-time constant so they can be either built-in types or struct. More precisely, they cannot be a class instance.
public class Complex { }
public struct Point
{
public Complex complex;
public Point(int any)
{
complex = new Complex();
}
}
static class Program
{
static void Method1(Point p = new Point()) { }
//static void Method2(Complex c = new Complex()) { } //cannot be compiled
static void Main()
{
Method1();
// Method2(); cannot be compiled
}
}
What I don't understand is why can a struct encapsulating a class be a compile-time constant recall that a class instance is not a compile-time constant?
Upvotes: 2
Views: 593
Reputation: 564373
It is not a compile time constant. Your Point call is allowed as optional arguemnts can be:
In this case, you're using the 2nd allowed option for optional arguments - an expression of the form new ValType()
, as a struct
is a value type.
The fact that your value type encapsulates a class doesn't matter - you get the default value for the value type (which will have complex
set to null
).
Upvotes: 2