Monday 6 January 2020

Dynamic vs var in C# with example

When we have var which dynamically holds any type or value so why we need dynamic type, what are the differences and situations where we can use dynamic rather than var, there were some question in my mind so I explored more which I want to share here.
There are two things, static type and strong type checking, with static type checking the compiler will produce an error for any call that fails to pass a method argument of the appropriate type, likewise, you should expect a compiler error if you attempt to call a missing method on a type instance. On the other hand Dynamic type checking contradicts the idea that the type of a variable has to be statically determined at compile time, the difference with dynamic type checking is that the check occurs when the program executes rather than when it compiles.
Dynamic type is introduced with C# 4 (Visual Studio 2010), dynamic is a type. It has a very special meaning, but it’s definitely a type and it’s important to treat it as such. You can indicate dynamic as the type of a variable you declare, the type of items in a collection or the return value of a method. You can also use dynamic as the type of a method parameter. Conversely, you can’t use dynamic with the typeof operator and you can’t use it as the base type of a class.
A major difference between the two keywords is that var can only appear within a local variable declaration. You can’t use var to define a property on a class, nor can you use it to specify the return value or a parameter of a function.
Let’s see some examples:
  1. var str = "some string";
  2. Console.WriteLine(str.Length);
  3. string str = " some string ";
  4. Console.WriteLine(str.Length);
In this case both are identical; in both cases str knows that str.Length means the string.Length property.
Now let’s check the same with dynamic type
dynamic str = "some string "; Console.WriteLine(str.Length); 
In this case str is dynamic type and does not know anything about string.Length property, because it does not know anything about str at compile time.
Let’s try this
dynamic str = "some string "; Console.WriteLine(str.abcd); 
If you will try to compile, it will compile successfully but at run time it will give error.

No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...