kiss my armpit
kiss my armpit

Reputation: 3519

Why can a struct encapsulating a class be a compile-time constant?

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

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564373

It is not a compile time constant. Your Point call is allowed as optional arguemnts can be:

  • a constant expression;
  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
  • an expression of the form default(ValType), where ValType is a value type.

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

Related Questions