Search code examples
c#typeofdefault-parameters

Why doesn't C# allow a typeof as a default parameter?


class MyClass
{
    public void MyMethod(Type targetType = typeof(MyClass))
    {
    }
}

Isn't typeof(MyClass) a compile-time constant?


Solution

  • From MSDN - Named and Optional Parameters:

    A default value must be one of the following types of expressions:

    • 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.


    typeof does not necessarily return a compile time constant as it may return different results depending on context.