var vs. dynamic in C#

This is going to be a very short article talking about var vs dynamic features in C#. var is a new keyword added to .NET 3.5. var is a new way to declaring variables in C#. In other words, instead of specifying the type of the defined variable, the compiler is going to figure out the data type of the declared variable.

For example, you can use var deceleration keyword instead of using int in the following lines.

  1.  int x = 3;
  2.  var y = 3;

For your information, both previous lines are exactly the same. Where the first line was written using int keyword to declare an integer variable; whereas, the second line used var to let the compiler figure out the value type. Both of the variables, x and y are integers variables.

This is helpful especially in complicated declared types when using LINQ.

dynamic was introduced in C# 4.0 where it is a new way to declare objects and variables. The main objective is that to let the compiler ignore type checking during the compile time, and force it during the run-time. If you rewrite the previous example using dynamic, you will not notice any difference in the execution.

  1.  dynamic z = 3;

The only difference is that the compiler has no idea about the data type of the variable z during the compile-time, but during the run-time. This is why it is called late bound.  This could be useful in certain matters where you need to deal with interoperability for example.

To recap, var is considered as early binding where data type determination and method lookup are done during compile-time; whereas, dynamic is a late bound where data type and method lookup are carried out through the run-time using reflection. Thus, we can conclude syntax checking happens during compile-time and typos must be corrected before program execution when using var; while dynamic syntax could throw errors during the run-time as syntax checking never happens before execution. To illustrate the last point, consider the following example:

  1. var s1 = “Hello”;
  2. int n1 = s1.Leng;
  3. dynamic s2 = “Hello”;
  4. int n2 = s2.Leng;

notice that the property name is wrong on purpose, Line 1 has a syntax error as type checking took place during the compile time. Unlike var, using dynamic is not going to highlight any syntax error in compile-time (Line 4 has no problem during compile-time), but an error will be thrown during the run-time after type checking takes place and property lookup-operation fails to find a property with the name ‘Leng’.

Post a comment or leave a trackback: Trackback URL.

أضف تعليق