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)
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.
There is nothing wrong with that, as long as the code is clear.
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 !
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With