-4

Possible Duplicate:
Use of var keyword in C#

Which one is better? using var in variable type declaration or using true type like int , ... ? Why?

Which one is better?

public class A
{
   var v1 = 0;
   var v2 = string.Empty;
}

or

public class B
{
   int v1 = 0;
   string v2 = string.Empty;
}
Community
  • 1
  • 1
masoud ramezani
  • 22,228
  • 29
  • 98
  • 151

4 Answers4

2

As gdoron says, there's no right or wrong answer, but in the interests of opinion, I'll give mine.

I generally always explicitly use the type, rather than var because I find it is easier to understand what type something is. E.g, for someone else reading your code, it's clear what the type is.

In your example, it's hardly noticeable and a casual reader can easily see what is a string and what is an int. However, consider:

var f = SomeFunction();

To the eyes, it's not clear what the type of f is immediately.

That said, var can be useful when doing something like:

var userMap_ = new Dictionary<string, User>();

as that surely saves some typing and it's clear what the type is.

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
  • `var` reduces the noise from the code. Like with collections, I don't care if It's `List` or `T[]` or `IEnumerable` – gdoron Mar 14 '12 at 10:38
1

Which one is better? blue shirt or green shirt?

What you like the most. There is no right answer for this one.

By the way:

  • You spelled class wrong.
  • There can't be var declaration in the class level, only in a method body...
gdoron
  • 147,333
  • 58
  • 291
  • 367
1

As @gdoron says however if you simply have an int and a string I think I would use the true type.

Jon
  • 38,814
  • 81
  • 233
  • 382
0

In the string case var is less typing, so there its better. For 3 letter types I'm indifferent and undecided.

Jodrell
  • 34,946
  • 5
  • 87
  • 124
  • 1
    I wouldn't say that it's a good idea to decide depending on how many letters you have to type. Not a good programming practice – Oskar Kjellin Mar 14 '12 at 10:35
  • So, what is the purpose of `var` then? If not to save typing and read parsing. – Jodrell Mar 14 '12 at 10:36
  • Check the dupe above. I didn't say that one of the reason isn't to save typing. What I said is that you cannot decide from case to case depending on how many letters you have to type. Just because int is three letters doesn't mean you shouldn't use var and so forth – Oskar Kjellin Mar 14 '12 at 10:37
  • I do agree ofc, but in the presented example both types were explicitly stated. – Jodrell Mar 14 '12 at 10:40