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

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...

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" ;         ...

SSIS package - set oledb connections at runtime

SSIS oledb connection manager does't allow user to connect to different oledb servers. If we store oledb connection sting in Config file then it will accepts server name, InitialCatalog and username. But it wont accept password. The is because oledb connection manager has not exposed the oledb password property. To over come this problem we have to override the OLEDB connection manager itself. So that it accepts connections to different oledb servers. Public Sub Main() Dim vars As Variables Dim oledbConnectionManager As ConnectionManager oledbConnectionManager = Dts.Connections("<oledb connection name>") ' ADDED TO MAKE oledb CONNECTION STRING DYNAMIC Dim oServerName As String Dim oUserName As String Dim oInitialCatalog As String Dim oPassword As String Dts.VariableDispenser.LockOneForWrite("oServerName", vars) oServerName = vars("oServerName").Value.ToString().Trim() vars.Unlock() Dts.VariableDispenser.LockOneForWrite("oInitia...