How to define dynamic data types in C#


You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time. C# 4.0 introduced the dynamic type that avoids compile time type checking.

The following is the syntax for declaring a dynamic type −

dynamic <variable_name> = value;

Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time.

Let us see an example −

dynamic a = 25;

To get the type of dynamic variable −

Example

using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {
         dynamic a = 25;

         Console.WriteLine(a.GetType().ToString());
         Console.ReadLine();
      }
   }
}

Updated on: 20-Jun-2020

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements