Dynamic vs Var vs Object

May 6, 2012 2 comments

C# by nature is a very strongly typed language which signifies that most of the verifications are executed statically during compile time. If not all, but most of features and structs exposed by C# language adheres to this principle. With the introduction of Dynamic in C#4.0, I found there is confusion in developer’s community around the difference between Var, Object and Dynamic.
In this blog, I will try to highlight the difference from CLR and compiler’s perspective.

All the objects (value and referenced types) in managed environment are directly or indirectly inherit from System.Object. With this inheritance in place, a variable of System.Object can hold the reference of instance of any type.

In above example, o1 is holding the reference of XmlDocument and o2 is holding the reference of boxed double value. However in either case, compiler will allow to call only those methods /properties which exists in System.Object type. In other words compiler will not allow you to call ChildNodes property from o1 and similarly o2 cannot be used for any arithmetic operation. All of these restrictions are in place because from compiler’s perspective, o1 and o2 are holding the reference of System.Object type. The only way to access the ChildNodes property is to typecast it into XmlDocument type. In that case, compiler will emit the code to validate the type casting during runtime.

a)Though variable of System.Object type can hold the reference of any type, compiler will ensure the type safety. If type casting is happening, compiler will emit the code to validate the type safety during runtime.
b)Assigning the value type to a variable of System.Object will suffer from Boxing / Unboxing.

Var Keyword
Var keyword was introduced in C# 3.0. It was primarily introduced to support the notion of anonymous types (which was the key requirement for LINQ). But important part is, var is resolved at the compile time, i.e. the actual type is resolved by the compiler during the compile time. Hence it provides same type safety as using normal typed variable.

In above example, var1 is resolved by compiler as double, var2 is resolved by compiler as int and var3 is resolved by compiler as string. From CLR perspective, there is nothing known as var.

a) Var is a compile time feature resolved to a valid underlying type. Due to this, compiler enforces you to assign a value during the declaration so it can infer the actual type.
b) Since var is resolved to a valid type during compilation, compiler will enforce all type safety and code will not suffer from boxing / unboxing.

In my own opinion, we should use “var” ONLY when actual type is not known during development i.e. type is anonymous as shown in following example.

If the actual type is known, then I will not recommend using var to save few keyboard strokes as it reduces the readability of code.

With C# 4.0, Microsoft introduces “dynamic”. When you define a variable of type dynamic, compiler internally performs two steps. The first thing compiler does is, it converts the type to System.Object and then it postpones all the type validation to the runtime. The following example uses the dynamic to declare an int type.

In above example, Double declares the multiplier as dynamic. During compilation, dynamic will be converted to System.Object and compiler will emit the code for type safety during runtime as shown in the following IL.

a) During compilation time, dynamic is converted to System.Object and compiler will emit the code for type safety during runtime.
b) As dynamic is treated as System.Object, it suffers from boxing / unboxing similar to System.Object.
c) Since compiler emits the code for all the type safety, application’s performance will suffer.

Dynamic was introduced only to simplify the access to the COM APIs. I strongly recommend that we should restrict the use of dynamic only when handling the COM APIs as it might cause runtime exceptions and can cause performance issues.

Tags: , ,

Why ParameterizedThreadStart is not a generic delegate

May 6, 2012 Leave a comment

When you create a new thread, you pass the thread method either in shape of ThreadStart delegate or ParameterizedThreadStart delegate. The only difference between these two delegates is that later one takes an argument so we can pass an argument to the underlying thread method when starting the thread.

I am not sure why Microsoft have not declared the ParameterizedThreadStart as generic delegate so we can pass an object of type T rather than object. I personally think, this way compiler can not only enforce the type check, but can further avoid boxing / unboxing. The generic version could be

public delegate void ParameterizedThreadStart<T>(T argument);

Tags: ,

Constructor And Initialization Statement

October 14, 2009 Leave a comment

In most of OOP languages, it is widely accepted that base constructor is always called before child class constructor. In other words all base class variables get initialized prior to initialization of any child class variable. C# language works slightly differently. In C# language, if child class constructor is not calling the base constructor explicitly, then C# compiler will insert a calling statement of base class default constructor. Theoretically it should be the first statement in the child class constructor. But in reality that’s not that case. If you are having any initialization statement in your code then it will be executed first before base class constructor is called as shown in following diagram:


Following diagram shows the IL code of child class constructor where it base class contractor call statements appears after child class initialization statement.


Therefore during the initialization statement in child class, the base class variables are not initialized and for this reason, C# compiler does not allow you to access the base class variables in the initialization statement as shown below:


Tags: ,

Anonymous Delegate with Control.Invoke

September 29, 2009 Leave a comment

If you attempt to call control invoke method (as shown below) with an anonymous delegate, you will encounter the compiler error “Cannot convert anonymous method to type ‘System.Delegate’ because it is not a delegate type”.

Anonymous Delegate with Control 1

The reason for this error is that compiler can not determine the signature of the anonymous method. For compiler to compile the anonymous method, it must know its signature and compiler finds this information from the corresponding delegate. Since Control.Invoke method accepts a delegate class which is an abstract class, thus compiler can not find its signature and throws the error.

To resolve this issue, we need to type cast the delegate into any delegate that does not take any parameter as shown below:

Anonymous Delegate with Control 2

Tags: ,

Why should one write a blog

August 28, 2009 Leave a comment

There is no single reason to write a blog, as it very much depends on your motivation. Nevertheless, blogging can have a number of benefits, whether it is to help boost the presence of your business online, or just to share and debate ideas with like-minded people.

In one of his post, Jeremy Wright describes the blog as “Blogging’s something for anyone and everyone. I can’t think of anyone who can’t benefit from knowing more people, never forgetting a thought again and improving on their thoughts with little or no effort.”

But blogging can be a time sinkhole. Joel Libava, a Cleveland entrepreneur who runs his own franchise consulting business, started the Franchise King blog four years ago. He says that only in the past year has he noticed a big impact from his blog writing. All that typing finally paid off. “As opposed to going out to seek franchise candidates, I found that they seek me now,” Libava says


Get every new post delivered to your Inbox.