X

Using var keyword in C#

Keyword var is cool thing we can use to make our code more readable for other programmers and why not – reviewers. But var can also be used to make our code difficult to understand. In this case, lte’s say, we are overusing var. So, var is like wine – if one takes glass of it then everything is okay in the morning, but if somebody takes it couple of bottles then the morning will be awful. Or let’s say – too much var will kill you?

Let’s see some nice scenarios how to use keyword var. I try also tell you what happens in my head when I see one or another example of these. So, using var we can write:

var messagingService = new MessagingService();

instead of:

MessagingService messagingService = new MessagingService();

Okay, it’s simple. I mean both cases. For longer class names var is like gift from heaven that makes our code readable again. But I can also survive first example, no proble. The information I need is there – the name of class, so I know what is the type of object I have to use.

Sometimes we don’t really care much about types. By example, we may need some automatic types in our code:

var stuff = new { X = 100, Y = 200 };

string[] words = { "chat", "stick", "many", "terror" };

var upperLowerWords =
    from w in words
    select new { Substr = w.Substring(1), Upper = w.ToUpper() };

This code is clear (also in the mean that soon will some authorities contact me because of one of those strings). There are some autometic types and we can look at their definitions to find out what they have to offer.

Now let’s see how to confuse other developers who are reading our code.

var x = tmpObject.Search(criteria);

Why this is confusing? Well, to be honest, it is confusing because we gave a method fuzzy name. Giving properties and methods an informative names is deeper art than we first can expect. But this blog entry is not about naming stuff.

The point is that the example above hides some information that we may be interested in – what is the type of var? We have to go to Search() method and check out what it returns. Huh, very unconvenient, isn’t it?

Liked this post? Empower your friends by sharing it!
Categories: C#

View Comments (3)

  • Good observations. I have been loving using the "var" keyword, but I definitely agree that is is inappropriate in some places.

  • Yes, Greg, it does. But when I'm reading the code I don't want any avoidable problems to interrupt my mindwork.

Related Post