chris carter's web log

Home |  Contact |  Admin
 

C# Var : The Religious War

Posted on July 14, 2008      1 Comment(s)

OK.  So I had no clue when I posted previously about the C# var keyword that the use of var is a religious war that's going on right now.  I'm not sure where I stand right now, I'd have to say, "it depends". 

I wouldn't use it in my current work, it would confuse other devs not up on the var usage and would unnecessarily complicate things at this time. 

I'm also not sure due to the fact that people far smarter than me are on both sides of the fence, so right now is a good time to sit back and REALLY think before introducing var into my everyday code.

Getting Started With MonoRail and VS2008 Screencast

Posted on July 14, 2008      0 Comment(s)

This is an 11 minute(or so) long screencast demonstrating how to pull down the latest bits from the castle folks and get a monorail project up and running. It goes through configuration and creating a simple controller/view using the build from 7/11/2008 off of the castle build servers.

View It!

Here's the code used for the solution. I've included the bin directory from the castle download, so the project is just over 5 megs.

C# Var

Posted on July 14, 2008      0 Comment(s)

I've been seeing a lot of people posting code examples that have the C# var keyword sprinkled liberally through their code. It's a handy little feature that helps you with LINQ queries, anonymous types, etc. For example, you can create a new type on the fly like this:

var person = new { Name = "Chris" };
Console.WriteLine(person.Name);
1
2

Not everyone reads from left to right, but I do, as does every single person who works with me and every single blog and code example I've ever seen. This is important when considering the liberal use of var because now one would have read a whole line of code and figure out the type for themselves, rather than just reading the first word on the line(if declaring a local variable).

Look at the following snippet:

var bus = FacilityConfig.Children["bus"];
if (bus == null)
  throw new InvalidOperationException("bus is a mandatory element");
1
2
3

What type is bus in the previous example? You would have to hope that you're in visual studio and can hover over it with the mouse pointer so you could see the type which is lame.

The var keyword should be used sparingly, only when the type is unknown, like in a linq query that returns an anonymous type. Using it in situations where you know what the type is makes your code hard to read.