Dynamic, object, var

With the beginning of the dynamic and DLR types in .NET 4, I now have 3 options, declaring what I call "open" types:

  • var , locally implicit types, to underline the "what" instead of the "how",
  • object , an alias for System.Object and
  • dynamic , disable compiler checks, add methods / properties at runtime

As long as there is a lot written about it, nothing I have found unites them, and I must admit, it is still a bit fuzzy.

Add to that LINQ, lambda expressions, anonymous types, reflection ... and it gets more shaky.

I would like to see some examples of possibly comparable advantages / disadvantages to help me strengthen my understanding of these concepts, as well as help me understand when, where and how I should choose between them.

Thanks!

+7
source share
5 answers
  • Use var to keep your code short and readable, or when working with anonymous types:

     var dict = new Dictionary<int, List<string>>(); var x = db.Person.Select(p => new { p.Name, p.Age }); 
  • Use dynamic when dynamic linking is useful or required. Or when you need to decide which method to call based on the runtime type of the object.

  • Use object as little as possible, prefer to use certain types or generics. One place where it is useful when you have an object used only for locking:

     object m_lock = new object(); lock (m_lock) { // do something } 
+5
source

var exactly the same as writing a full type, so use this when the variable must be of the same type. It is often used with LINQ , as you often use anonymous types with LINQ.

object is the root of all classes, so it should be used when the variable will have many different, unrelated / not inherited instances, or when you do not know the compilation time of the type declaration (for example, reflection). This should usually be avoided.

dynamic for objects that are dynamic in nature, because they can have different methods and properties, they are useful for interacting with COM, as well as dynamic and domain-specific languages.

+3
source

var : I use it for short code:

instead of writing:

 MyFramework.MyClass.MyType myvar = new MyFramework.MyClass.MyType(); 

I can keep it short:

 var myVar = new MyFramework.MyClass.MyType(); 
+2
source

var is a static type, so Type is known at compile time and at runtime (so it helps to catch typos)

dynamic very similar to objects, but is not limited, as it would be with Object methods, here Type is displayed at run time, it will be used in cases where you want to achieve some dynamic behavior.

Well for Object it doesn’t have such members that you would use, Generics would be more preferable in such cases

+1
source
0
source

All Articles