Who ritualistically uses the C# "var" keyword?

I’ve been using C# for over a year ago.
Honestly, I still don’t make use of the “var” keyword.
I always explicitly state the type.

I read the C# language specification, and it’s worded in a way that suggests that if you don’t use the keyword, then you are programming incorrectly.

Does anyone else tend to not use the var keyword?
I just cannot get into a habit of using it. It never even crosses my mind to use it.

This is what the MSDN site says:

Implicitly Typed Local Variables

  • Use implicit typing for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.

It’s useful in a couple of cases.

  • To avoid nonsense such as Dictionary<string, List>.
  • To reduce direct dependency on types defined in third party libraries.

But I wouldn’t call not using it bad practice. Ultimately it’s just syntactic sugar. Under the hood typing a variable explicitly and using car are identical.

4 Likes

I generally don’t use it, but sometimes it does help with readability. In the case below there’s also no problem knowing what the “var” is.

// instead of this...
Dictionary<SomeLongNamedType, AnotherLongType<GenericType>> someDescriptiveName = new Dictionary<SomeLongNamedType, AnotherLongType<GenericType>>();

// we can have this:
var someDescriptiveName = new Dictionary<SomeLongNamedType, AnotherLongType<GenericType>>();
5 Likes

If I am not mistaken, var was introduced for anonymous types. It has been grossly overused. Personally, I prefer implicit types and var when needed. However, when using code snippets for say foreach, which by default uses var, I leave it.

Var is just a compiler trick, and will generate the appropriate type when compiled. If you are not using an IDE that can catch improper casts then var can become an enemy.

1 Like

Using var everywhere really hurts readability- so I don’t use it that often.

When I’m trying a lot of different things, var can mean a lot less typing. For instance, sticking var in a foreach loop means I can change the type of the collection without breaking anything. While it may not be necessary in the end, it’s a nice practical tool.

var comes in very handy when using LINQ and Lambda functions of course, as I’m sure others will mention.

3 Likes

If you’re using var, you should be using JS because only jerks type that crap and expect people to actually be able to maintain and read code better than explicitly type variable definitions.

tl;dr use var’s if you’re a jerk.

3 Likes

No, I do use var all. the. time. It saves me a lot of keystrokes and it makes the code far more readable, particularly for those long type names or nested generics as @mikael_juhala example. You already have the type explicitly defined on the right side, why would you need it on the left side again? So yes, it definitely increases readability by decreasing repetitions.

How does it hurt readability?

@LaneFox

I’m using var all the time and I’m not a jerk, jerk. Don’t confuse C# var with JS var. C# var is strongly-typed. The type is inferred by the compiler, but it is strongly-type nonetheless. Whereas JS var allows to change type at runtime, C# var does not. You get a compilation error if you try:

var str = "hello!";
str = 1.0f; // Compiler says "Nope."

However, if you really want to change the type at runtime you have to use the dynamic keyword, though this is not supported by the Mono version used by Unity.

2 Likes

You don’t need to be disrespectful just because you don’t like to use it.

3 Likes

Could vary between IDE’s, but I find it easier to tell some things apart with the type on the left side. Some constructors may look similar at a glance, so its nice to not have to hover over to find out what it is.

1 Like

I mix and match, if it is obvious from the constructor I will use var and if if the type name will be crazy long due to generics I will use var. Also useful for LINQ since that always returns something like IEnumerable and can get long if your T also has a generic.

To be fair if you are unsure of the type and need the ide to tell you that is generally on a usage of the type not where it is declared.

If you care about the official specification, the general consensus is to use var as little as possible. Just search “C# var,” paying extra attention to the StackOverflow discussion. They cite the MS C# sites use of the word “rarely.”

But as far as Unity, remember that Unityscript was the starting language, and one of the advantages was you didn’t need to know about types, at first. Being able to use (roughly) var n=3; var name=“Jorlin”; was considered an advantage for new users. And then there’s sometimes an instinct to use every language feature where ever it can be used. Especially if you’ve just learned it.

My thinking is that whether or not to use var is a distraction. It sucks concentration away from things that will actually matter. Deciding never to use it, and never to even think about using it will probably result in better programs.

2 Likes

Have you ever used LINQ? If not then that’s most likely why.

https://blogs.msdn.microsoft.com/danielfe/2005/09/22/linq-what-is-the-purpose-of-var/

What do you mean? A constructor literally defines the type.

var obj = new GameObject();

It’s more than obvious that obj is of type GameObject. Repeating the type on the left is redundant.

2 Likes

It never occurred to me to use var.
I don’t have any LINQs … that I know of. :smile:

Looks handy; does it work in Unity?

Yes

1 Like

You’re right of course, I was wrong about constructors.

1 Like

As a ritual? nope… no I don’t.

Do I use it? Yes, yes I do.

It’s a very useful tool, especially when constructing objects of very long type names.

PlayerRangedWeaponAnimationController controller = new PlayerRangedWeaponAnimationController();
//or as a component
PlayerRangedWeaponAnimationController controller = this.AddComponent<PlayerRangedWeaponAnimationController>();

//vs

var controller = new PlayerRangedWeaponAnimationController();
//or as a component
var controller = this.AddComponent<PlayerRangedWeaponAnimationController>();

Yeah… I kinda prefer the ladder.

There is also the anonymous typing, like with linq, where it’s extremely useful (primarily since the type name is unkown otherwise).

Of course, if ‘var’ hurts the readability… I’ll probably avoid it. This could happen if say a function returns an object, and the method name isn’t exactly descriptive as to what the type is.

var obj = otherObj.GetChild(0);

A very distinct one would be:

for (var t in transform)

… sort of forces you to know the api… not as readable (also, since transform defaults to IEnumerator, as opposed to IEnumerator, t is now typed object rather than Transform like you want).

As for this though…

I agree that MSDN sometimes is very authoratative with its standards and naming things… it says similar things about the ‘_’ and also parts of the documentation suggesting you should never say “fire event” but rather “raise event”, despite other parts of the documentation using the phrase “fire” anyways.

This sort of thing does annoy me, and is often the fault of the documentor writing that specific bit of documentation, or the culture of the product changing over time.

But… as the phrasing of the use of ‘var’ goes in the quote above… I don’t take it as saying you’re programming incorrectly. But rather as stating the situation you would use it.

Which is the places most people DO use it. Because it’s useful.

Use it when the variable is obvious (like with new) or when type is not important (like with anonymous types).

I think you might be reading too far into it if you’re taking anything more from it then that.

That’s what a hammer is for!

5 Likes

I’m getting an “error CS0103: the name “var” does not exist in the current context” message when I write this:

var obj = new GameObject ();

which is an example given in a previous post here.

The var keyword should be used whenever it the type of the object is obvious. It’s more concise and it makes it easier to refactor your code. This is a change being seen in many languages, and is universally liked. For example in C++11 there is a new auto keyword that does the same thing as var.

Think of it this way, if you’re saying Vector3 pos = transform.position;, why are you even saying Vector3? You know the position is a Vector3. All positions are a Vector3. Instead, say var pos = transform.position;. It’s both less typing, still perfectly clear (assuming the reader has even the most cursory understanding of Unity) and easier to refactor. If the type of the right hand side changes, you don’t have to change the type on the left-hand side.

I think the most important (and also smallest) change is that of noise. Having all these types for variables adds a lot of noise to the code, it makes it harder to read, it makes it longer than it has to be, it makes it more horizontal than it needs to be. It’s a good change, and it’s a good practice to get into.

There are times when you shouldn’t use it though. Like var num = someUnknownFunction(); is a bad thing. Presumably you don’t know what someUnknownFunction returns, you should be manually defining the variable type here to annotate a function that’s not used very often. Here that extra information is welcome, it’s a notice to other coders or your future self that this is a float or something. Yes, you could do the same with a comment, but comments add unnecessary noise to the code that should not be there unless there’s a real reason. I know “self-documenting code” is often used as an excuse not to write comments or documentation, but it’s a real thing. If you write your code simple and clean enough that it’s easily apparent what’s going on, you generally don’t need to write excessive comments or detailed documentation. Annotating your code with types when the type is not clear is very useful here.

1 Like