dynamic variable in c#.net

 

Dynamic Type

In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time

Ex:

dynamic num = "hi";

when I  say num. , you will not get any intelligence as it will resolve at runtime

when I declare like

int num = "hellow";

it throws exception while compilation time itself. but we declare using dynamic it wont give compile problem

dynamic num = "hellow";

num++;

 even, the above also didnt any compilation issue, but at runtime it throws exception.

Example demo:

using System;

namespace DynamicDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            int i = 50;

            long l = i;

            Console.WriteLine($"int i = {i} & long l = {l}");

            Console.ReadKey();

        }

    }

} 

it wont give problem, but if i change it to

long l = 50;

int i = l;

 

Why we use dynamic in C#?

In C#, we have several built-in data types such as string, int, bool, double, DateTime, etc. All these are static data types, meaning type checking and type safety are enforced only at compile time.

it is not advisable to use the dynamic type unless you are integrating with a dynamic language or another framework where types are not known at compile time.

Because the compiler does not know what type the dynamic variable will eventually become, it’s unable to offer method or property code hints in Visual Studio

Comments

Popular posts from this blog

Email Sending through O365 using OAuth Protocol

IoT Technology

What is reverse proxy?