Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Are Dynamic Parameters Boxed

Tags:

If I have:

void Foo(dynamic X) {
}

And then:

Foo(12);

Would 12 get boxed? I can't imagine it would, I'd just like to ask the experts.

like image 635
Adam Rackis Avatar asked Feb 10 '11 14:02

Adam Rackis


2 Answers

Yes, it will.

Under the hood, a dynamic type is just an object with some meta-data, so value-types will get boxed when put into a variable, field, or parameter of type dynamic.

The method will actually be compiled as this:

void Foo([Dynamic] object X)
{
}

Read more about the DynamicAttribute here.

IL for code calling it:

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 8
    L_0000: nop 
    L_0001: ldc.i4.s 12
    L_0003: box int32
    L_0008: call void ConsoleApplication13.Program::Foo(object)
    L_000d: nop 
    L_000e: ret 
}
like image 111
Lasse V. Karlsen Avatar answered Sep 23 '22 13:09

Lasse V. Karlsen


Yes. A value type needs to be boxed in order to type check.

like image 43
Aliostad Avatar answered Sep 22 '22 13:09

Aliostad