The advantage of the var keyword in C # 3.0

Duplicate:

What to use with the var or object name type

I could not understand the need for the var keyword in C # 3.0. What is the advantage of using. I saw this question, but did not understand the real purpose of its use.

+3
source share
7 answers

It is mainly introduced for LINQ, when you can use an anonymous type as a projection:

var query = from person in employees where person.Salary > 10000m select new { FullName=person.Name, person.Department }; 

Here, the query type cannot be declared explicitly because the anonymous type does not have a name. (In real cases, an anonymous type often includes values ​​from several objects, so there is not a single class that contains all the properties.)

It is also practically useful when you initialize a variable using a potentially long type name (usually due to generics) and simply call the constructor - this increases the density of information (reduces redundancy). There is also the 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 expresses it in a more compact way.

Of course, this can be abused, for example,

 var nonObviousType = 999999999; 

but when it’s obvious what a type variable is, I think it can significantly increase readability.

+23
source

The main reason for its existence is the introduction of anonymous types in C #. You can create types on the fly that don't have a name. How would you indicate your name? Answer: You cannot. You just tell the compiler to make them for you:

 var user = users.Where(u=> u.Name == "Mehrdad") .Select(u => new { u.Name, u.Password }); 
+3
source

This is a shorthand way to declare var. Although "int i = new int ()" is not much to print, when you start to get longer types, you get a lot of lines that look like this:

 SomeReallyLong.TypeName.WithNameSpaces.AndEverything myVar = new SomeReallyLong.TypeName.WithNameSpaces.AndEverything(); 

In the end, someone knew that the compiler already knew what type you declared, thanks to the information you used to initialize var, so it would not be too easy to ask the compiler to do the right thing here.

+2
source
  • Linq expressions do not return a predefined type, so you need to use the "generic" declaration keyword to capture this and other places where anonymous types are used.
  • Used carefully, it can simplify refactoring by separating the type of the returned method from the variable that captures it.
  • Having the same name on the same line twice for the same operator is really stupid. It is a pain to type something like this:

.

 ReallyLongTypeName<SomeOtherLongTypeName> MyVariable = new ReallyLongTypeName<SomeOtherLongTypeName>(); 
+1
source

Here are some benefits.

  • Less text input without loss of functionality
  • Increases the security of your code. The foreach loop using the iteration variable that is introduced in var will catch the silence that are introduced with explicit types
  • This makes it so that you do not need to write the same name twice in the variable declaration.
  • Some functions, such as declaring a strongly typed local variable of type anonymous type, require the use of var

Shameless self-promotion. I wrote a blog entry on this subject some time ago, when I thought that using var is appropriate and contains relative information for this topic.

+1
source

In short:

  • minimize the need to type the variable twice
  • necessary to support anonymous types, for example. as returned by LINQ queries
0
source

The real need for the var keyword was to support anonymous types in C # 3.0, which in turn should have properly supported LiNQ (Language Integrated Querying).

Without using var, you can never do something like this:

  var person = new { Name = "Peter", Age=4}; 

This means that you could not execute the following linq query because you did not 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 obvious if you start creating more complex linq queries with multiple levels of returns and joins.

The fact that you can use var in other ways to not print something like IEnumerable<Dictionary<List<string>,IOrderedCollection<DateTime>> myBadDesign = getBadDesignController().BadDesignResults("shoppingCart"); it's just a side effect / bonus if you are a lazy typer =)

There are flaws in readability if you start calling vars in disparate places, but if you use var for a strong type, and the compiler can determine the type of your variable, than any reader should also define it.

0
source

Source: https://habr.com/ru/post/1436079/


All Articles