Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How's memory allocated for a dynamic variable .net 4.0?

Tags:

.net

c#-4.0

dynamic is a implicit or explicit type allocation ? How memory allocation occurs for dynamic variables in context of below example at runtime.

dyanmic impact on type safety as C# is type safe language.

public class Program
{
    static void Main(string[] args)
    {                                                
        dynamic dynamicVar = 10;
        dynamicVar = true;
        dynamicVar = "hello world";
        // compiles fine
        int index = dynamicVar.IndexOf("world");                        
    }        
} 
like image 844
Deepak Avatar asked Sep 12 '13 07:09

Deepak


People also ask

How dynamic memory is allocated?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.

What is dynamic memory allocation in C# net?

The dynamic array provides dynamic memory allocation, adding, searching, and sorting elements in the array. Dynamic array overcomes the disadvantage of the static array. In a static array, the size of the array is fixed but in a dynamic array, the size of the array is defined at run-time.

Where are dynamic variables stored in memory?

Dynamically allocated variables live in a piece of memory known as the heap, these are requested by the running program using the keyword "new". A dynamic variable can be a single variable or an array of values, each one is kept track of using a pointer.

How memory is allocated to a variable?

When a variable is declared compiler automatically allocates memory for it. This is known as compile time memory allocation or static memory allocation. Memory can be allocated for data variables after the program begins execution. This mechanism is known as runtime memory allocation or dynamic memory allocation.


1 Answers

A variable of type dynamic is effectively a variable of type object as far as the CLR is concerned. It only affects the compiler, which makes any operations using a dynamic expression go through execution-time binding.

That binding process itself will use extra local variables etc (take a look in ILDASM, Reflector or something similar and you'll be staggered) but in terms of dynamicVar itself, the code you've got is just like having an object variable - with appropriate boxing for the int and bool values.

like image 179
Jon Skeet Avatar answered Nov 15 '22 04:11

Jon Skeet