Reputation: 4944
Given the following code:
void Main()
{
dynamic[] arr = { 5, "test2", "test3"};
foreach (var i in arr)
{
Console.WriteLine(i.GetType().Name);
}
}
it prints the following:
Int32
String
String
I can't understand how can an array has elements of different types. From a C background, array elements should be having the same type and each element should take the same amount of RAM. Because in C, something like arr[i]
would be equivalent to *(arr + i)
and the pointer arr
would move i * sizeof(arr data type)
steps.
Upvotes: 1
Views: 2116
Reputation: 34947
dynamic[] arr = { 5, "test2", "test3"};
results in object[]
(you can see if you call arr.GetType()
).
The array contains objects of the same type; in this case the type is object
.
The elements in your array are boxed. This passage is from Boxing and Unboxing (C# Programming Guide).
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object instance and stores it on the managed heap.
An object[]
array, even for value types, does not contain the objects themselves; it contains references to them (btw. string
is a reference type in C#).
Again, this is from Boxing and Unboxing (C# Programming Guide).
dynamic
in C#
I think the first sentence from Using type dynamic (C# Programming Guide) could clarify how dynamic works in C#.
C# 4 introduces a new type,
dynamic
. The type is a static type, but an object of type dynamic bypasses static type checking.
The quote from Built-in reference types (C# reference) may even be better.
The dynamic type indicates that use of the variable and references to its members bypass compile-time type checking. Instead, these operations are resolved at run time. (...)
Type dynamic behaves like type object in most circumstances.
Upvotes: 7
Reputation: 4796
Remember that in C#, all classes inherit from Object
.
An Object[]
array is actually an array containing pointers to the actual objects, so the size is always the same.
The memory would look like this :
A dynamic[]
array will be casted to Object[]
, therefore accepting any data type in there.
About structure, which don't inherit from Object
, the run-time uses a trick called boxing to put the structure inside an object, therefore allowing the structure item to enter the array.
Upvotes: 1
Reputation: 1131
A dynamic
type will be stored as an object but at run time the compiler will load many more bytes to make sense of what to do with the dynamic
type. In order to do that, a lot more memory will be used to figure that out. Think of dynamic
as a fancy object.
Upvotes: 0