Dynamic Keyword in C# 4.0 with example

 

Welcome Friends..! my name is Gurunatha Dogi, Let me introduce one of the new language features of C# 4.0. "Dynamic Keyword" was introduced in C# 4.0 (.NET Framework 4.0 with Visual Studio 2010).

What is Dynamic Keyword

Dynamic keyword was introduced in c# 4.0 i.e. it was introduced in the dot net framework 4.0 i.e. available from visual studio 2010.

In C# 4.0 microsoft team has introduced this "dynamic" keyword because to achieve dynamically statically typed object which will bypass compile-time checking but during runtime it coverts himself to strong type depending on attached data and do the error-checking. So "dynamic" keyword is called as static type.

Programming language is divided into two parts one is static type language and another is dynamic type language. Static type language is a language whose type-checking is done at compile time and on the other hand dynamic type language is a language whose type-checking is done at runtime.

Static types : int, string, double, long

Dynamic types : object, arraylist, class objects.

Dynamic keyword is a static type where this static type bypasses the compile time error-checking but does an error-checking on the runtime. It is a static type but unlike other static types like int, double it does not do an error-checking on the compile-time infact it bypasses the compile time error-checking logic but does that error-checking on the runtime.

In simple words the type of variable declared is decided by the compiler at runtime time and all erros with caught only at compile time.

On the compile-time dynamic keyword object acts just like dynamic types i.e. similar like an object but on runtime it gets converts to a strong type depending on the data attached.

Before we will see an examples on dynamic keyword. Let us first understand how to create a dynamic type object.

Syntax of Dynamic Keyword

To create a dynamic keyword in c# 4.0 its pretty simple just we need to write dynamic keyword followed by dynamic object name as sample is shown below.


class SampleClass{

  dynamic anyobjectname = "test";

}

Compile Time and Runtime Test

Test 1 : Strong Type object checking on Compile Time

Here in this test we will take any strong type object and test whether it throws an error during compile time. So do the testing we will be using our console application.

class Program
    {
        static void Main(string[] args)
        {
            int a = "Guru";

        }
    }

As you see from above we took the strong type data-type i.e. "int" "a" and assigned a string value. The moment we assigned the string value visual studio intellisense automatically throws an compile time error which says "Cannot implicitly convert type 'string' ".

Conclusion : So it is proved that strong type shows and an error on the compile time and further it does not allow code to execute.

Test 2 : Dynamic object checking on Compile Time

class Program
    {
        static void Main(string[] args)
        {
            object a = "Guru";

        }
    }

Above code does not thrown any compile error on compile time.

Conclusion : So it is concluded that dynamic objects does not show any compile time error it bypasses the both compile-time checking.

Dynamic keyword is internally a wrapper of reflection why because like reflection it can also do dynamic invocation during runtime the only the difference is it does not inspect any metadata information of an assembly like reflection does.

Reflection during runtime before dynamic invocation it inspects the metadata information of an assembly after inspecting the metadata information it does the dynamic invocation.

Reflection can be seen on visual studio IDE directly when you create any object of string, int, array, double etc then using that object just click on DOT (.) operator the moment you click on the (DOT) visual studio intellisense shows up all related methods, properties of a class (data-type of object). For more information on reflection see this link.

Dynamic Keyword Resolved at Runtime

So when you create an object using a dynamic keyword an example is shown below.

class Program{

 static void Main(string[] args){

    dynamic emplname = "";
   
    emplname.
   
 }

 
}

The moment you click on (DOT) visual studio intellisense could not able to find any methods or properties this because "dynamic" keyword is resolved on runtime, On creation it is just a general object and during runtime depending on data-type like

if "integer" data


    class Program
    {
        static void Main(string[] args)
        {
            dynamic str = 4;

            Console.WriteLine(str.GetType());

        }
    }

During the runtime dynamic keyword "str" turns into strong-type (int). Output is System.Int32.

if "string" data


 class Program
    {
        static void Main(string[] args)
        {
            dynamic str = "Khadak Bist";

            Console.WriteLine(str.GetType());

        }
    }

During the runtime dynamic keyword "str" turns into strong-type (string).Output is System.String.

if "double" data


class Program
    {
        static void Main(string[] args)
        {
            dynamic str = 99.999;

            Console.WriteLine(str.GetType());

        }
    }


During the runtime dynamic keyword "str" turns into strong-type (double).Output is System.Double.

So by seeing above examples it is been proved that during runtime dynamic keyword turns into strong type and uses reflection internally for a dynamic invocation.

Simple Example of Dynamic in C-Sharp.NET 4.0

class clsTravelDetails
    {

        private int _travelcode = 0;
        private string _travelagent = "";

        public int TravelCode
        {
            set
            {
                _travelcode = value;
            }
            get
            {
                return _travelcode;
            }
        }

        public string TravelAgent
        {
            set
            {
                _travelagent = value;
            }
            get
            {
                return _travelagent;
            }
        }


        public void TravelDetails()
        {
            Console.WriteLine("Agent Code : {0}  Agent Name : {1} ", TravelCode, TravelAgent);
        }

    }

As you see from above code that we have created a class called "clsTravelDetails". Now we will create an object for class "clsTravelDetails" and use it in our main program of Console Application.

    class Program
    {
        static void Main(string[] args)
        {
            dynamic objtravel = new clsTravelDetails();

            Console.WriteLine(objtravel.GetType());
            Console.WriteLine("\n");

            objtravel.TravelCode = 9;
            objtravel.TravelAgent = "Allwyn Borde";

            objtravel.TravelDetails();
            Console.WriteLine("\n");

            

        }
    }

Output

As you see depending on attached data i.e. "clsTravelDetails" it gets converted into a strongly typed object of class "clsTravelDetails".

Difference Between Dynamic Keyword and Object Keyword

Objects are dynamic types.

Dynamic is a static type.

Objects are not strongly typed.

Dynamic are strongly typed during runtime.

Objects need type casting.

Dynamic does not need any type casting.

Objects are derived from System.Object.

Dynamic uses reflection internally for a dynamic invocation.

Let's see a simple example of using dynamic and object keyword

class Program{
        static void Main(string[] args)
        {
            object abc = 5;
		    Console.WriteLine(abc.GetType());
            abc = abc + 5;

        }
}

Above code will not execute why because in the 3rd like it will throw an compile error that "Operator '+' cannot be applied to operands of type 'object' and 'int'". So as you see it is compulsory to type-cast an object where needed and once type casting is made then compiler will not throw an compiler error. But an object is still not safe why because it is not strongly-typed thus we can type-cast with any data-type and compiler will bypass without type-checking but on runtime it will throw an error.

class Program
    {
        static void Main(string[] args)
        {
            try
            {
                object abc = 5;
                Console.WriteLine(abc.GetType());
                abc = (string)abc + 5;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }

            

        }
    }

Output

So it is concluded that object keyword are not safe to use and since they are not strongly-typed objects.

Now let's try same code with dynamic keyword.

class Program
    {
        static void Main(string[] args)
        {
            try
            {
                dynamic abc = 5;
                Console.WriteLine(abc.GetType());
                abc = abc + 5;
                Console.WriteLine("Output is " + abc);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }

            

        }
    }

Output

Above code is neat and clean code which executed smoothly and no need worrying about wrong type-casting.

So compared to object keyword, dynamic keywords are safe to use since they dont need any type-casting and bypass compile time checking and turns into strongly-typed object. If you are not sure about data-type during compile time and during run-time only it will confirmed then it is best practices to use dynamic keyword because it gives "Statically Dynamically Typed Objects".

Difference Between Dynamic Keyword and Reflection

Dynamic keyword was introduced in C# 4.0 framework and uses reflection internally.

Reflection is derived from System.Reflection namespace.

Dynamic keyword does not do any inspection of meta-data of an assembly for dynamic invocation and method calls are made by the compiler is least bothered if those methods exist or not.

Reflection on otherhand it inspects meta-data of an assembly for dynamic invocation.

Both dynamic and reflection are used to operate during runtime environment and for dynamic invocation.

Dynamic can invoke only public methods and properties.

Reflection can invoke both public and private functions and properties.

Dynamic does caching internally.

Reflection does not do caching.

Conclusion : Use dynamic keyword when you do not want to inspect any meta-data of a DLL and do not want to invoke private memvers.

Use reflection when you want to inspect meta-data of a DLL and want to invoke both public and private members.

So friends..!Thank you very much for reading this article if you have any doubts please feel free to drop your queries in the comment section below and do not forget to share this article with your friends on social media networks.

Kindly spread this article on your Facebook, Twitter Google+ channels to share your knowledge.

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Aug
04
2014

Understand Reflection in C#.NET with example

CLICK TO READ FULL ARTICLE

Views - 22919 |Category - C#

Jul
23
2014

Understand Constants in C# with an example

CLICK TO READ FULL ARTICLE

Views - 8158 |Category - C#

Jul
13
2014

Understand Enums in C# with an example

CLICK TO READ FULL ARTICLE

Views - 18943 |Category - C#

Jun
16
2014

Understand the use of Override Keyword and New Keyword in C# with Example?

CLICK TO READ FULL ARTICLE

Views - 11611 |Category - C#

Jun
06
2014

Understand params parameter with an example in C#?

CLICK TO READ FULL ARTICLE

Views - 12269 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

833lv

 

 
Comments

Posted by Sanjaythomas on 2015-01-19

Its very clear on Dynamic and Object key word. KEEP IT UP. thanq, sanjay.