6

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");                        
    }        
} 
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
Deepak
  • 420
  • 5
  • 21
  • 1
    Below are some of the discussions on `stack` which might be useful: http://stackoverflow.com/questions/7478387/dynamic-and-performance http://stackoverflow.com/questions/2690623/what-is-the-dynamic-type-in-c-sharp-4-0-used-for – Pratik Sep 12 '13 at 08:31

1 Answers1

5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks Jon .. but I want to ask one question in above code that, at runtime compiler uses reflection to understand the type on bases of value and evaluate the method "IndexOf" or it directly cast type based on value type. – Deepak Sep 12 '13 at 08:58
  • @Deepak: Yes, it uses reflection basically. (For types implementing IDynamicMetaObjectProvider it will do rather different work, but for "simple" types it's effectively just reflection.) – Jon Skeet Sep 12 '13 at 08:59