Why use dynamic typing in c#? - c#

At first I thought something like:
var aName=getAllSomethings();
Is very unreadable, and so I'll use dynamic typing just when there's no room for confusion such as:
AClassName aName = new AClassName();
Here,
var aName=new AClassName();
seems readable.
But than I read (here) that dynamic typing also comes with a price in performance.
I tried reading all the other posts in that link to understand where I should use dynamic typing, but couldn't come up with even one good reason. Should I just wait for when I'll tell myself - "This can only be solved with dynamic typing" ? Or are there better (practical) reasons for using it?
Thanks.
Edit: My mistake (-: will close this question ASAP.

var isn't dynamic typing. It's just that the type of aName is inferred by the compiler.
Your example is still entirely statically typed, and has no performance penalty. Your code is compiled into exactly the same IL as it would be with an explicit type name.
Now in C# 4, dynamic typing does exist, but it would be written as:
dynamic aName = new AClassName();
My personal belief is that dynamic typing will be relatively rarely useful in C# 4 - basically when you're dealing with data which is already only known dynamically, e.g. reflection, or navigating XML.

This is not dynamic typing. The var declares a static type known at compile time and it will be absolutely equivalent to declaring the type name. The compiler will infer the type and replace it in the resulting assembly.

Using the var keyword isn't dynamic typing. The var keyword is handled by the compiler. The variable gets statically typed based on the first assignment to the variable.
The type of:
var value = new StringBuilder();
Is StringBuilder. There's no way to change that type (which is what dynamic typing would allow).
What Jon Skeet is referring to in his blog is the dynamic keyword. That is a whole other beast.

That isn't dynamic typing. Dynamic typing is through the "dynamic" type (oddly enough). Using var has no overhead at all, it is a coding shorthand that still produces strongly typed variables.

You are misunderstaninf why dynamic typing is.
"var" uses Type Inference to deduce at compile time the type of the variable. It's mechanism is fairly straighforward, and has absolutely no performance impact. A variable declared with "var" can still only be one exact type (or derivations of that type).
Dynamic variables allow a variable to hold any type at runtime, and still perform operations on that object as if we know what is supports. Each of these calls makes the runtime perform a check to see if the method call is actually supported. That is part of why dynamic typing has a runtime overhead.

As everyone else has mentioned, the 'var' keyword does not give us dynamic typing. The type is inferred at compile time.
I use var when I think it makes sense; namely, when the type is obvious and it cuts down on the verbosity of a declaration:
var someDict = new Dictionary<string, int>();
Instead of...
Dictionary<string, int>() someDict = new Dictionary<string, int>();
However, in your example here:
var aName=getAllSomethings();
I wouldn't use 'var' because, as you have noticed already, you then have to check the return type of 'getAllSomethings()' (bad naming style for C# BTW) in order to know what 'aName' is, which just makes the code less readable.

Related

Dynamic, Object, Var

With the inception of the dynamic type and the DLR in .NET 4, I now have 3 options when declaring what I call "open" types:
var, locally implicit types to emphasize the 'what' instead of the 'how',
object, alias for System.Object, and
dynamic, disable compiler checks, adding methods/properties at runtime
While there's a lot written about these out there, nothing I've found puts them together, and I have to confess, it's still a bit fuzzy.
Add to this LINQ, lambda expressions, anonymous types, reflection... and it gets more shaky.
I'd like to see some examples, perhaps contrasting advantages/disadvantages, to help me solidify my grasp of these concepts, as well as help me understand when, where and how I should pick between them.
Thank you!
Use var to keep your code short and more 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 binding 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 using specific types or generics. One place where it's useful is when you have object used just for locking:
object m_lock = new object();
lock (m_lock)
{
// do something
}
var is exactly the same as writing the full type, so use that when a variable should be of a single type. It is often used with LINQ since you often use anonymous types with LINQ.
object is the root of all classes, and so should be used when a variable will have many different, unrelated/not inherited instances, or when you do not know the type ad compile time (e.g. reflection). It's use should generally be avoided if possible.
dynamic is for objects that are dynamic in nature, in that they can have different methods and properties, these are useful for interacting with COM as well as dynamic languages and domain specific languages.
var: I use it for keeping code short:
instead of writing:
MyFramework.MyClass.MyType myvar = new MyFramework.MyClass.MyType();
i can keep it "short":
var myVar = new MyFramework.MyClass.MyType();
var is statically type so the Type is known at compile and runtime (so helps catch typos)
dynamic very much similar to objects but not limited as it would be with the Object methods, here the Type is inferred at runtime, it would be used in cases wherein you want to achieve some dynamic behaviour.
Well for object it ain't having any such members which you would be using, Generics would be more preferred in such cases
Have look on this article it gives advantages and limitations of Dynamic keyword.

In C#, how do inferred variables using var behave with respect to memory and lifecycle?

Ok, I've been reading everything I can find on var, and I'm pretty sure I've got a handle on their basic behaviors and type inference. I've always been a big proponent of explicit types, so var makes me a little edgy when I'm reading code. So I have a couple of questions regarding its memory usage and the behavior of a variable declared with var over the course of that variable's lifecycle in memory.
Since var is an inference to an explicit or anonymous type, will its memory be allocated in the same place its corresponding type would be or is var universally created on the heap and accessed as if it were an object. As an example:
int i = 5; // puts this on the stack
var i = 5; // does this also go on the stack?
Does a declared var have a constant type once it is initialized or can it be adjusted as well? I ask this because I can't find in the documentation that specifies this, and I just read something in this SO question by #Eric Lippert:
a variable is a storage location whose
contents change
Having tested the following code, I see an implicit conversion exception even at the IDE level. I don't have the experience with LINQ at this point to run a similar test with respect to anonymous types. Do they follow this same behavior? Will the IDE recognize a type mismatch at design time or would such code receive a run-time exception?
var i = 5; // Initializes as int, value is 5
i = "Steve"; // Type casting error
Finally, is there ever a situation that you can think of where you may know a type at design time but it would be prudent to use var anyway? I ask because I've seen code samples where people do this, and from what I've read it strikes me as just lazy-coding.
EDIT: I realize there are a lot of articles talking about this topic, but I haven't found any that answer these questions specifically (though some hint one way or another). I would be happy to read any document you feel is relevant to these topics, just please post a link.
var is 100% syntactic sugar in the C# compiler. When the actual IL is generated, the type is explicitly defined. var-declared variables do not behave any differently from their explicitly-defined counterparts. The dearth of information you're seeing is coming from the fact that var is simpler than you're assuming. There is quite literally no difference between these two lines:
var i = 10;
int j = 10;
(Other than the fact that you see the words var and int, of course; they are functionally completely identical).
var variables are infered by the compiler, they are really just syntactical sugar, there is no difference between:
var i =0;
and
int i = 0;
in the compiled code.
They were added for the purpose of allowing anonymous types, e.g.
var MyVar = new { prop1="A string", prop2=5};
Yes var varables recognise a type mismatch at compile time, the compiler dynamically creates a class for them when it compiles. e.g. the below would not compile:
var MyVar = new { prop1="A string", prop2=5};
MyVar = "Fred";
As others have said, var has no effect on how the variables behave in terms of memory - it just means you don't specify the name. For anonymous types you couldn't specify the name, first because you don't know it at compile time, and second because the names are deliberately "unspeakable" - they're not valid in C#. (Generally they contain <> for example.)
The IL generated for code using var and code using an explicit name is exactly the same. Just as a normal variable can't change type, nor can a variable declared using var... so in your example where you try to assign the value "Steve" to a variable which has an implicit type of int, you'll get a compile-time error exactly as if you'd explicitly declared it to be of type int.
As for when to use var and when not to, I have a few rules of thumb:
Obviously if you want the variable to have a type other than the compile-time type of the assigned expression, you've got to do it explicitly
For constructor calls, it's always clear what the the type is even if you're using var
var is useful for emphasizing what the code is meant to do rather than how
Often I use var if the explicit name would be extremely long - particularly for generics with multiple type arguments.
Basically it's all about readability: if the code is easier to read using var, go for it. If not, don't. Note that this isn't the same as saving typing... code is generally read more than it's written, so think about your reader. Eric Lippert wrote a great note when tech reviewing the first edition of C# in Depth, which is worth a read.
Simple answer: exactly the same as normal variables.
var declarations are translated into specific (strong) types at compile-timee. var is simply a method of automatic type inference, and has nothing to do with dynamic languages. At the end of the day, it's just the compiler being clever and translating var into what actual type you want.
"Since var is an inference to an explicit or anonymous type, will its memory be allocated in the same place its corresponding type would be or is var universally created on the heap and accessed as if it were an object"
The important thing about var, is that the compiler changes the var statement to the actual type at compile time, so:
var number = 1;
Will get changed to:
System.Int32 number = 1;
...by the compiler. And as such the memory locations for storage of these types is no different. var is essentially syntactic sugar. So, method local declarations of value types will get stored on the stack, reference pointers will get stored on the stack with the referenced objects on the heap.
Once you have declared a variable as var, because this is translated into its full type by the compiler, you can't then dynamically change the type:
var i = 5;
i = "Steve";
...is invalid, because its already been declared as an Int32.
Anonymous types follow a similar behaviour, where a type is created by the compiler during compilation.
"Finally, is there ever a situation that you can think of where you may know a type at design time but it would be prudent to use var anyway?"
Personally, I follow a simple pattern:
For primitives, I always put the type:
int i = 5;
string name = "Matt";
For complex types, I mostly do this:
var instance = new MyComplexTypeInstance();
For LINQ results, I stick to var:
var result = from i in something select i;
For methods, if the method is descriptive of the type being returned, then I will use var.
var instance = GetInstance();
Whereas, more complex method names, I'd put the actual type:
Result result = DoSomethingWeirdAndWonderful();
Each developer will find something they are comfortable with, the choice is yours. As var is only really a design-time thing, its all syntactic sugar.

Advantage of var keyword in C# 3.0 [duplicate]

This question already has answers here:
Closed 13 years ago.
Duplicate:
What to use var or object name type
I couldn't understand the need of var keyword in C# 3.0 What is the advantage in using it.
i saw this question but did not understand the real purpose of using it
It's mostly present for LINQ, when you may use an anonymous type as the projection:
var query = from person in employees
where person.Salary > 10000m
select new { FullName=person.Name, person.Department };
Here the type of query can't be declared explicitly, because the anonymous type has no name. (In real world cases the anonymous type often includes values from multiple objects, so there's no one named class which contains all the properties.)
It's also practically useful when you're initializing a variable using a potentially long type name (usually due to generics) and just calling a constructor - it increases the information density (reduces redundancy). There's the same amount of information in these two lines:
List<Func<string, int>> functions = new List<Func<string, int>>();
var functions = new List<Function<string, int>>();
but the second one expresses it in a more compact way.
Of course this can be abused, e.g.
var nonObviousType = 999999999;
but when it's obvious what the type's variable is, I believe it can significantly increase readability.
The primary reason for its existence is the introduction of anonymous types in C#. You can construct types on the fly that don't have a name. How would you specify their name? The answer: You can't. You just tell the compiler to infer them for you:
var user = users.Where(u=> u.Name == "Mehrdad")
.Select(u => new { u.Name, u.Password });
It's a shorthand way of declaring a var. Although "int i = new int()" isn't too much to type, when you start getting to longer types, you end up with a lot of lines that look like:
SomeReallyLong.TypeName.WithNameSpaces.AndEverything myVar = new SomeReallyLong.TypeName.WithNameSpaces.AndEverything();
It eventually occurred to someone that the compiler already knew what type you were declaring thanks to the information you were using to initialize the var, so it wouldn't be too much to ask to just have the compiler do the right thing here.
Here are a couple of advantages
Less typing with no loss of functionality
Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types
Makes it so you don't have to write the same name twice in a variable declaration.
Some features, such as declaring a strongly typed anonymous type local variable, require the use of var
Shameless self promotion. I wrote a blog entry on this subject awhile back that dived into when I thought the use of var was appropriate and contains relative information to this topic.
http://beta.blogs.msdn.com/jaredpar/archive/2008/09/09/when-to-use-type-inference.aspx
Linq expressions don't return a predefined type, so you need a 'generic' variable declaration keyword to capture that and other places where anonymous types are used.
Used carefully, it can make refactoring easier by decoupling a method's return type from the variable that captures it.
Having to put the same name on the same line twice for the same statement is really kind of silly. It's a pain to type something like this:
.
ReallyLongTypeName<SomeOtherLongTypeName> MyVariable = new ReallyLongTypeName<SomeOtherLongTypeName>();
In short:
minimize the need for typing the variable type twice
essential in supporting anonymous types, e.g. as returned by LINQ queries
The real need for the var keyword was to support anonymous types in C# 3.0--which in turn were required to properly support LiNQ (Language Integrated Querying).
Without using var you could never do something like this:
var person = new { Name = "Peter", Age=4};
Which means that you couldn't execute execute the following linq query because you wouldn't know how to assign it to a variable:
[var/sometype] dogsFixedQuery = from myDog in kennel select new {dogName = myDog.FirstName + " " + myDog.OwnerLastName, myDog.IsNeutered, dogLocation = kennel.Address};
The utility of anonymous types will be more apparent if you start to create more complex linq queries with multiple levels of returns and joins.
The fact that you can use var in other ways to avoid typing out something like IEnumerable<Dictionary<List<string>,IOrderedCollection<DateTime>> myBadDesign = getBadDesignController().BadDesignResults("shoppingCart");
is just a side-effect/bonus in case you're a lazy typer =)
There are cons for readability if you start calling vars in disparate locations but if you're using var for a strong type and the compiler can determine the type of your variable than any reader should be able to determine it as well.

var keyword in C# 3.0 [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What’s the point of the var keyword?
Hello everyone,
I want to confirm whether my understanding is correct. If I do not use LINQ, then the only benefit of using var is to make brevity? Is that correct understanding?
No, you can use var to construct anonymous types, regardless of whether or not you're using LINQ:
var anon = new { Name = "Anonymous", Age = 42 };
It's also easier for working with types like this. When you have very long generic types, the type name can get in the way of visually identifying the variable name as part of a declaration.
Dictionary<string, Dictionary<int, ICollection<object>>>
especially if you go back through and change it to
Dictionary<string, IDictionary<int, ICollection<object>>>
From msdn:
Beginning in Visual C# 3.0, variables
that are declared at method scope can
have an implicit type var. An
implicitly typed local variable is
strongly typed just as if you had
declared the type yourself, but the
compiler determines the type. The
following two declarations of i are
functionally equivalent:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
MSDN Link Here
If you're not using LINQ, var allows you to only declare the type of the variable once, instead of twice.
Example
var myObject = new MyObject();
vs
MyObject myObject = new MyObject();
This can only be done locally, and is also useful for declaring anonymous types.
Example
var myAnon = new { Name = "Something", Count = 45 };
Other than for LINQ queries I would be very cautious in using the var keyword. There are specific instance when you just need an anonymous type but this is few and far between I think. Var can lead to very confusing code as you have no idea what the type you are dealing with when reading the code unless you use the intellisense crutch.
It worries me more and more that I see so many snippets and bits of code that do the following... it's lazy and not what the var keyword was intended for:
// Not too bad but still shouldn't be done because the only gain you have is keystrokes
var Something = new SomeObject();
// Type here is not obvious, are you getting an int, double, custom object back???
var Something = GetLengthOfSpaghettiCode();
So use it for LINQ... use it for anonymous types (if you do use anonymous types outside of LINQ you should really scrutinize why you need to).
Quote from MSDN (very last line of article) regarding use of var:
However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.
Don't use it as a short cut to save keystrokes, the next guy looking at your code will appreciate it.
Pretty much, yes. var may be used wherever the compiler can infer the type of the variable from whatever value you are assigning to it. (The type inference rules are quite complex however, so you may want to read the C# specification for a full understandin.)
It's not quite correct in that the var keyword is required for defining anonymous types. For example:
var foo = new { abc = 1, def = 2 };
which can be used outside of LINQ queries as well as inside, of course.
I don't think using var should be a problem - and I prefer it for exactly the reasons of code readability. First of all, var is only syntactic sugar and just gets compiled away to a proper type when IL is emitted. And as far as the code readability goes, it makes more sense to focus on the purpose the variable is used for, and how it is assigned than just its type. VS .NET editor shows the type in the line following it anyway - if you just hover on it. So this shouldn't be a problem at all. And as far as the debugging goes - if you see Autos/Local/Watch windows - they display the types of all the members.
It makes more sense for me to see code like this:
var customers = GetCustomerList();
foreach (var customer in customers)
{
customer.ProcessOrders();
}
as opposed to
List<CustomerObjectDeserializedFromWebService> customers = GetCustomers();
foreach (CustomerObjectDeserializedFromWebService customer in customers)
{
customer.ProcessOrders();
}
var is in its fairness limited to using in local variable declarations which are also initialized at the time of declaration. And in that one case, if you omit the actual type it definitely improves readability IMO.
EDIT: And it would unfair on my part not to warn against the usages as below:
var x = 20;
This is not good; when the literal is applicable to multiple types, you need to know the default type of the literal and hence understand what is infered for the type of x. Yes, by all means, I would avoid such declarations.
I believe it is also used in the WCF (Windows communication Foundation) when dealing with data obtained via webservices and the like.
I've also found that the use of var also eases refactoring in low-coupled designs. This is because we tend to strong type variables, but normally the code that follows is expecting weaker types. Using var you'll offset type changes to the compiler.

Using implicitly typed local variables [duplicate]

This question already has answers here:
Why would var be a bad thing?
(18 answers)
Closed 8 years ago.
I just installed a trial version of ReSharper and one of the first things I noticed is that it always suggests to replace explicitly typed local variables with implicitly typed ones, e.g:
public string SomeMethod(int aParam)
{
int aNumber = SomeOtherMethod(aParam);
// should be changed to:
var aNumber = SomeOtherMethod(aParam);
}
I think explicitly typed variables are more readable (more explicit).
What do you think about ReSharper's suggestion? Is there any advantage in using implicitly typed variables? When do you use implicit/explict vars?
I personally only use “var” when I can clearly distinguish the variable Type by just reading the declaration, for example:
var someVariable = new List<int>();
In the example above, its evident that “var” refers to “List<int>”.
I don’t like to use “var” when I have to go to some method definition to find out what variable type “var” represents or by having to rely on visual studio intelli-popup or whatever that is called, for example this in not ok to me:
var someVaraible = SomeMethod();
I mean, what is the “SomeMethod” function supposed to return? Can you tell just by looking at the line of code? No you can’t, so that is why I avoid using “var” on those situations.
There's a lot of discussion about this, but I think it all comes down to personal taste, just like using the 'this' keyword almost everywhere.
I personally prefer explictly typed variables, but when using nested generic collections things can become more readable using an implicitly typed variable. Look at:
Dictionary<string, Dictionary<string, string>> myDictionary = new Dictionary<string, Dictionary<string, string>>();
vs:
var myDictionary = new Dictionary<string, Dictionary<string, string>>();
EDIT: this SO topic covers the same topic, with some nice replies: What to use: var or object name type?
EDIT2: Working a lot with async nowadays, I find that using explicity typed variables can sometimes prevent nasty bugs. Consider this silly example where you would want to return the Id of a user. Also consider that GetUserAsync returns a Task<User>. If you use implicitly typed variables, you would end up using something like this:
public long GetUserId()
{
var user = GetUserAsync();
return user.Id;
}
This compiles, but it is wrong. 'user' is actually a Task<User>. And it compiles as Task also has an Id property. In this case, one would accidentally return the Id of a Task instead of the User.
public long GetUserId()
{
User user = GetUserAsync();
return user.Id;
}
The above does not compile, as the compiler will complain that you cannot cast a Task to a User. Adding the await keyword of course solves this.
I've actually had this happen to me once :-)
Just in case some haven’t noticed yet, you can easily change the “suggestions” in Reshaper (Reshaper -> Options -> Languages -> Context Actions -> “Replace explicit type specification with ‘var’”).
I personally prefer to have explicit type specifications everywhere, but I'm not too fussy about it.
It's just easier to type the var pseudo-keyword at times than a huge type name, especially if a generic could be involved. However, you should know they're functionally identical. There's no performance difference or anything either way. The compiler derives the type of the right-side of the assignment and replaces var with that type. It's not happening at run-time like a VB variant.
FWIW, the var keyword is plainly readable in many cases. Especially if...
The right-side of the assignment is a constructor expression.
var map = new Dictionary>();
Local variables have good names.
HTH

Categories

Resources