Skip to main content

The Dynamic Primitive Type in C#


Runtime type identification made easy! Read on how new ‘dynamic’ type helps.

Let us look at the problems in versions prior to 4.0. A lot of times, we create programs that act on information unaware of its type until at runtime. A type-safe programming language like C# works with runtime-determined information during reflection and has to work a lot with strings which looks clumsy and cause performance problems as shown in the below example.

class Program
{
          public class MyType
         {
            public string MyProperty { get; set; }
          }
         static void Main(string[] args)
         {
             var myType = new MyType();
             var property = typeof(MyTestType).GetProperty("MyProperty");
             property.SetValue(myType, "Hello World", null);
         }
}

This is just a simple example which merely sets a property value of a type. Imagine how complex it would be and how clumsy your program would look if you have to Get \ Set ten different property values and then call ten other methods to perform various operations!!! It is no less than a nightmare to code and will have performance problems on top of it.

How C# 4.0 helps here: 
C# 4.0 brings in a cool new feature in the form of dynamic keyword which makes programmers life easy while working with runtime-determined information as in reflection. The C# compiler offers you a way to mark an expression’s type as dynamic. You can also put the result of an expression into a variable and you can mark a variable’s type as dynamic. This dynamic expression/variable can then be used to invoke a member such as a field, a property/indexer, a method, delegate, and unary/binary/conversion operators.

When your Code invokes a member using a dynamic expression/variable, the compiler generates special IL code that describes the desired operation. This special code is referred to as the payload.

At runtime, the payload code determines the exact operation to execute based on the actual type of the object now referenced by the dynamic expression/variable. Let’s try this on the same sample shown before and see how it makes life better.

class Program
{
       public class MyType
      {
          public string MyProperty { get; set; }
       }
      static void Main(string[] args)
     {
         dynamic myType = new MyType();
         myType.MyProperty = "Hello World";
     }
}

Isn’t it cool? Any expression can implicitly be cast to dynamic since all expressions result in a type that is derived from Object. Normally, the compiler does not allow you to write code that implicitly casts an expression from Object to another type; you must use explicit cast syntax. However, the compiler does allow you to cast an expression from dynamic to another type using implicit cast syntax:

Object o1 = 123; //OK:Imp cast
Int32 n1 = o1; //Err:No imp cast
Int32 n2 = (Int32)o1; //OK:Exp cast
dynamic d1 = 123; //OK:Imp cast
Int32 n3 = d1; //OK:Imp cast

The CLR will validate the cast at runtime to ensure that type safety is maintained. If the object’s type is not compatible with the cast, the CLR will throw an InvalidCastException exception. Sounds interesting? To know more, please refer to the following links: http://msdn.microsoft.com/en-us/magazine/ee336309.aspx and http://msdn.microsoft.com/en-us/library/dd264736.aspx

Comments

Popular posts from this blog

C# Generic Factory

Implement Factory pattern using generics     public interface IDoWork   {       string DoWork();   }     Declare an Interface first by abstracting the common  functionality    Here I am taking the example of DoWork     public class Manager : IDoWork   {     public string DoWork()     {         return "Manager Manages School" ;     }   }     Implement the IDoWork in concrete classes as shown      public class Teacher : IDoWork     {         public string DoWork()         {             return "Teacher teaches student in school" ;         ...

How to enable windows authentication in PostgreSQL

1.     Steps to create user or role in PostgreSQL ·         Open pgAdmin III ·         Login to PostgreSQL database ·         Select “Login Roles” and right click on mouse to view the context menu ·         Select “New Login Role” from context menu ·         Enter desired user name in “Role name” text box ·         Select “Definition” tab in “New Login Role” window ·         Enter desired Password in the given text box ·         Select “Role privileges” tab in “New Login Role” window ·         Select the privileges for the entered user or role ·         Select “SQL”...

UML - Association, Aggregation, Composition, Generalization, Specialization, Realization and Dependency

Association Association is a simple relationship between two classes. For example A relationship between Professor Class and Student class is known as Association. Both Classes can exist without each other, so Professor and Student are two independent classes. In this kind of relationships there will not be any owner class. Both classes have their own life cycle. UML Notation:     Aggregation Aggregation is a special type of Association. It is known as “Has-A” relationship. For example A Department class can contain Professor Class. Here Department class is owner class. Here in this relationship even after deleting Department class, Professor Class can exits. UML Notation: Composition Composition is a special type of Aggregation. It is known as “Is-A” relationship. For example A University Class has many Department class. Here University and Department objects are dependent on each other. If we delete Univ...