Friday, August 9, 2019

C# - Dynamic Type

C# 4.0 (.NET 4.5) introduced a new type that avoids compile time type checking,  it resolves type at run time.
dynamic myStr= "Ram";

myStr++;  // it wont give any error but when we run then it will through error.

Console.WriteLine(myStr.GetType().ToString());

A dynamic type changes its type at runtime based on the value of the expression to the right of the "=" operator.

dynamic myStr= 100; Console.WriteLine("Dynamic variable value: {0}, Type: {1}",myStr,
myStr.GetType().ToString()); 

compiler would not check for correct methods and properties name of a dynamic type therefore it will allow to write the method name which is actually not there in class. It will throw error at run time.

A method can have dynamic type parameters so that it can accept any type of parameter at run time. 
class Program { static void PrintValue(dynamic val) { Console.WriteLine(val); } static void Main(string[] args) { PrintValue("Hello World!!"); PrintValue(100); PrintValue(100.50); PrintValue(true); PrintValue(DateTime.Now); } }


Points to Remember :

  1. The dynamic types are resolved at runtime instead of compile time.
  2. The compiler skips the type checking for dynamic type. So it doesn't give any error about dynamic types at compile time.
  3. The dynamic types do not have intellisense support in visual studio.
  4. A method can have parameters of the dynamic type.
  5. An exception is thrown at runtime if a method or property is not compatible. 

 

No comments:

Post a Comment