Q: In the example below, is n
a value or by reference?
dynamic n = (int)2;
By default, unless otherwise specified:
Class instances, and Arrays, are reference types.
POD types, and possibly structs, are value types.
Conceptually, the value above could be thought of as a "dynamic POD type", or a "dynamic type containing a POD", either way it's not obvious which of the above rules should apply, if they both apply, this could lead to a contradiction.
To me, dynamic
feels as if it should behave like the value it holds, or otherwise be a reference type.
dynamic
is same as object
. Actually if you'll use decompiler (e.g. ILDasm), you will see
object n = 2
Or if you prefer IL code
.locals init (
[0] object
)
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: box [mscorlib]System.Int32
IL_0007: stloc.0
So n
is object and it's a reference type. And yes, you have boxing here. Even C# specification says that dynamic can be considered identical to object (4.7 The dynamic type):
dynamic is considered identical to object except in the following respects:
• Operations on expressions of type dynamic can be dynamically bound (§7.2.2).
• Type inference (§7.5.2) will prefer dynamic over object if both are candidates.