Thursday, October 31, 2013

var object

Last week we were doing some mob programming and a co-worker was telling the person doing the typing to type the following:

var object ...

Now, this obviously doesn't work and intellisense will yell right away, but we all knew that he did not mean what he said.  Either way, it was funny at the time and we got a laugh out of it.

After that meeting, I was working with another co-worker and we were doing some peer programming. One of the statements that we wanted to write something like the following:

var event = GetEvent();

Now, event in this case may be a sporting event so it would make sense to call it event.  The issue is that event is a C# keyword and cannot be used like this.  My question in both examples above is what if I want to call it an event and use event as the name?  The answer is to use the @ symbol in front of it.  For example the following would make the statement legal and will compile.

var @event = GetEvent();

Doing something like this in my opinion, as well as others, is bad practice and should not be done.  If you are wondering what we did, we just changed event to eventRecord and wrote it as follows:

var eventRecord = GetEvent();

Now, most normal people will stop there and call it a night.  I decided to do a few other tests with the var keyword, which after my tests make me think var isn't really a keyword, but some sort of almost keyword.  So, I did the following which is simple and straight forward:

var i = 5;
Console.WriteLine(++i);

For fun, I then changed it to the following and thought it would for sure blow up:

int var = 5;
Console.WriteLine(++var);

To my surprise, it compiled fine and ran fine.  This confused me and I thought it for sure was a bug or something else was wrong.  So, I decided to try something else.  What would happen if I changed int to var and wrote the following:

var var = 5;
Console.WriteLine(++var);

Would this work?  Should it work?

Well, it does work and it may have to do with some sort of backwards compatibility.  Since the var keyword was introduced in C# 3.0, previous code could have something like the following:

int var = 1;

This sort of makes sense because the assembly that is created will change the var to int.  The var is not included in the final assembly code and is just a C# thing.  I will provide another post about what your code looks like after it is compiled and then decompiled in the next couple days.

What's the point of all this?  Nothing, or maybe just to get me, or you, to think about things in more detail and share that knowledge.  Other than that, I think all my code will start off with var var ... just to see if someone complains and tells me to change it.

peace yo!

2 comments:

  1. can you explain this one? var far var far var far foo

    ReplyDelete
  2. I can't, but maybe ReSharper can. If not, then maybe seek medical advice.

    ReplyDelete