What are the benefits of implicit typing in C# 3.0 >+
Asked Answered
S

8

6

The only advantage I can see to do:

var s = new ClassA();

over

ClassA s = new ClassA();

Is that later if you decide you want ClassB, you only have to change the RHS of the declaration.

I guess if you are enumerating through a collection you can also just to 'var' and then figure out the type later.

Is that it?? Is there some other huge benefit my feeble mind does not see?

Superintendent answered 27/7, 2009 at 23:9 Comment(2)
And when I say "I guess if you are enumerating through a collection you can also just to 'var' and then figure out the type later." I know it's already typed at run time... I just meant in your logic.Superintendent
possible duplicate of Use of var keyword in C#Stocker
K
8

It's mostly syntactic sugar. It's really your preference. Unless when using anonymous types, then using var is required. I prefer implicit typing wherever possible though, it really shines with LINQ.

I find it redundant to type out a type twice.

List<string> Foo = new List<string>();

When I can easily just type var when it's obvious what the type is.

var Foo = new List<string>();
Knockwurst answered 27/7, 2009 at 23:12 Comment(5)
Its not purely sugar. It is required when working with anonymous types.Tansey
Correct, but even anonymous types are sugar as well.Knockwurst
That's like saying iterators are sugar. Sure you can build your own, but the compiler is actually doing a fair bit of work for you including nontrivial overrides on Equals, GetHashcode and ToString.Dav
@M4dRefluX: You could call a lot of things in C# "sugar", however I think a better term for it is lightweight compile-time code generation. There is a difference between simple syntactic prettieness, and the complex code generation that the C# compiler does for you when it takes things like LINQ queries, iterators, anonymous types, etc. and turns them into "normal" code. I would call anonymous delegates sugar, but I would call an anonymous type useful code generation that saves me time, effort, and money.Tansey
@jrista: I agree, they are definitely a time saver, just like the var keyword. I think we have different definitions. Syntatic sugar to me is a feature that saves me from typing redundant code.Knockwurst
O
5

var is useful for anonymous types, which do not have names for you to use.

var point = new {X = 10, Y = 10};

This will create an anonymous type with properties X and Y. It's primarily used to support LINQ though. Suppose you have:

class Person
{
    public String Name {get; set;}
    public Int32 Age {get; set;}
    public String Address {get; set;}
    // Many other fields
}

List<Person> people; // Some list of people

Now suppose I want to select only the names and years until age 18 of those people who are under the age of 18:

var minors = from person in people where person.Age < 18 select new {Name = person.Name, YearsLeft = 18 - person.Age};

Now minors contains a List of some anonymous type. We can iterate those people with:

foreach (var minor in minors)
{
    Console.WriteLine("{0} is {1} years away from age 18!", minor.Name, minor.YearsLeft);
}

None of this would otherwise be possible; we would need to select the whole Person object and then calculate YearsLeft in our loop, which isn't what we want.

Oliver answered 27/7, 2009 at 23:18 Comment(0)
T
4

I started what turned out to be a hugely controversial thread when I first signed on here (my choice of "evilness" to describe general use of var was obviously a terrible choice.) Needless to say, I have more appreciation for var than I did before I started that thread, as well as a better understanding of how it can be usefully used:

The evilness of 'var' in C#?

Some good reasons to use var:

  • Brevity
  • Reduction of Repetition (DRY)
  • Reduced refactoring effort
  • Supports anonymous types (key reason it was added to C#)
Tansey answered 27/7, 2009 at 23:12 Comment(0)
C
3

Have a look at this questions. Maybe they'll help you decide.

Use of var keyword in C#
https://stackoverflow.com/questions/633474/c-do-you-use-var

Contra answered 27/7, 2009 at 23:14 Comment(0)
E
2

It allows me to not repeat myself unnecessary. Consider this:

Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();

We have a very long typename repeated twice on the same line twice with absolutely no benefit. Furthermore, if you ever need to refactor this, you'll need to update the type twice. Whereas this is just as expressive:

var dict = new Dictionary<string, List<int>>();

There's still no doubt about type of dict here, but the code is shorter, and I would claim that it is easier to read as well.

Empyreal answered 27/7, 2009 at 23:17 Comment(0)
B
1

Actually "var" in C# is used to deal with anonymous type.

Like:

var t = new {number = 10, name = "test"};
Beret answered 20/6, 2013 at 14:27 Comment(0)
M
0

The overarching reason for the implicit typing was to support anonymous types, like those produced by LINQ queries. They can also be a big benefit when dealing with complex-typed generics...something like Dictionary<int,List<string>>. That's not too complex, but imagine enumerating...

foreach KeyValuePair<int,List<string>> pair in myDictionary
{

}

is simplified with implicit typing.

Mussorgsky answered 27/7, 2009 at 23:17 Comment(0)
V
0

While the var keyword was primarily introduced to support anonymous types, the main argument I've seen for using it more widely is for brevity/more readable code, plus fitting more on your line of code:

Dictionary<string, double> data = new Dictionary<string, double>();
versus
var data = new Dictionary<string, double>();

Though not a good reason for most people, I also like the var keyword as a blind programmer, as I listen to the code being read out and thus here the variable name after just one syllabul :-)

Vav answered 27/7, 2009 at 23:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.