Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 818
cazavientos Avatar asked Jan 20 '12 09:01

cazavientos


1 Answers

I am not a IL expert, but seems that it calls a method at L_0005:

return typeof(int);

It´s the same of:

.maxstack 1
.locals init (
    [0] class [mscorlib]System.Type typeofvar)
L_0000: ldtoken int32
L_0005: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
L_000a: stloc.0 
L_000b: ldloc.0 
L_000c: ret 

You can see that it isn´t a constant writing type of code:

const Type constType = typeof(int);

That returns a error:

Constant initialize must be compile-time constant
like image 59
Felipe Pessoto Avatar answered Oct 19 '22 23:10

Felipe Pessoto