Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it considered accepted using var's as "shortcuts" in c#?

Tags:

c#

One use for the var type in c# seems to be shortcuts/simplifying/save unnecessary typing. One thing that I've considered is this:

MyApp.Properties.Settings.Default.Value=1;

That's a ton of unnecessary code. An alternative to this is declaring:

using MyApp.Properties;

-- or --

using appsettings = MyAppp.Properties.Settings;

leading to: appsettings.Default.Value=1 or Settings.Default.Value=1

Abit better, but I'd like it shorter still:

var appsettings = MyFirstCSharpApp.Properties.Settings.Default;
appsettings.Value=1;

Finally, it's short enough, and it could be used for other annoyingly long calls too but is this an accepted way of doing it? I'm considering whether the "shortcut var" will always be pointing to the existing instance of whatever I'm making a shortcut too? (obviously not just the settings as in this example)

like image 327
Kristian Erik Tigersjäl Avatar asked Dec 20 '10 15:12

Kristian Erik Tigersjäl


4 Answers

It's acceptable code in that the compiler will take it and know what to do with it. It's acceptable code logically in that it shortens code later. It's really not any different than actually defining the variable type (int/bool/whatever) rather than saying var. When you're in the studio, putting your mouse of the variable gives you its compiled type, so there shouldn't be any real issue with it. Some might call it lazy, but laziness is the mother of invention. As long as your code doesn't become unreadable, I can't see how it would be much of a problem.

like image 160
Joel Etherton Avatar answered Sep 30 '22 02:09

Joel Etherton


There is nothing wrong with that, as long as the code is clear.

like image 32
SLaks Avatar answered Sep 30 '22 00:09

SLaks


In Fact, var is more and more used exactly for that : shortening the code.

Specially in the case of

MyClass myClass = new MyClass();

Which is very clear enough using

var myClass = new MyClass();

And btw, ReSharper helps you enforce that var is used everywhere it can be !

like image 21
VdesmedT Avatar answered Sep 30 '22 00:09

VdesmedT


Seems fine to me, it can enhance readability especially if you're using that long .notated syntax many times.

As a side, if you're using an indexed property or an autogenerated property (which does work on the fly for the GETTER) multiple times, then there can be a performance hit for each access of this property. That's microoptimisation though, so probably shouldn't worry too much about that.

like image 32
Tom Avatar answered Sep 30 '22 01:09

Tom