object vs var

I was inspired to write this short blog post by my colleague who watched me for a moment while I writing this code (code was shortened to be more understandable):

Type someObj.GetType t = ();
var propertyInfo = t.GetProperty ( “someProperty”);
object somePropertyValue = propertyInfo.GetValue (someObj, null);

After I had written this code, my college asked me why I didn’t use the keyword var instead of the keyword object. He was confused because I am well-known as a great proponent of the var keyword in our team. 
I couldn’t argue with him, and I agreed that his remark is valid
In this situation, it is better to use the keyword var instead of the object.

Before we continue,

I have to admit that I was not always a supporter of using var. I refused using the var keyword a long time. My arguments against keyword var were classic. Using keyword var reduces code readability
But I give it a chance, and I realized that using keyword var forces me to write better-named variables, and I can focus on the value of the variable instead of its declaration. For me, it is an another tool that you help to write cleaner code.
So generally speaking keyword var is good and you should use everywhere, BUT in the situation with my college which I mention in the first paragraphs, I was wrong.

To answer why we must finish the code which I mentioned above.

Whole code looked like this:

Type someObj.GetType t = ();
var propertyInfo =t.GetProperty ( “someProperty”);
object somePropertyValue = propertyInfo.GetValue (someObj, null);
propertyInfo.SetValue (anotherObj, somePropertyValue, null);

I never use variable somePropertyValue I just set its value to another property. In this case, I realized that keyword defining somePropertyValue as an object increases the readability of code.


Because when I’m reading this code, The type object emphasizes my intention that this variable is not used to make to call any method or read or set any data. 
This variable has just “transport” function. It only transmits some information. You could say that in this case, this variable is behaving as “dummy instance.” And it helps me to read the code in the future.

I want to emphasize that I know that it seems like a trivial thing. Use var or object in this situation. Who cares? But we are all aware how the programming is so complicated and challenging. So I believe every even slight improvement in readability can save our time and our nerves :)

This blog post is a translation of my older blog post written in the Czech language.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.