C# 3.0 (Orcas) - implicit variables

C#:
var Skoobideebop = new {UpperLeft = New Point{X = 0, Y = 0}, BottomRight = New Point{X = 5, Y = 5}};
First off, naming a variable Skoobideebop makes it unreadable. I think you're tyring to make a case for not using something by coming up with the worst things someone could do. Instead of blanket discouragement, we should be trying to come up with a best uses policy that works for everyone. "Don't use var with generics" sounds like a good one to me. It doesn't say "don't ever use var becuase someone might use it with a generic and make code unreadable" it simply advises against using var with generics which seems like a great idea.

So far we have:
1. Var shouldn't be used with primitives. This avoids possible mis-decleration.
C#:
var area = 25; //did I actually want a float here?
2. Var shouldn't be used with anonymous types. Var with anonymous types is extremely difficult to read.
C#:
var myRect = new {UpperLeft = New Point{X = 0, Y = 0}, BottomRight = New Point{X = 5, Y = 5}}; //uuhh...that's a rectangle, I think.  Lemme decihper that.
3. Use Var in cases when initializing a class with extremely long (>25 characters) class names. If the decleration goes off the page or onto several lines it is not as readable as it could be.
C#:
MyVeryLongGenericTypeName<MyVeryLongClassName> foo = new MyVeryLongGenericTypeName<MyVeryLongClassName>(...); //something.something.something.superlongclassname is another example of a long class name
//becomes
var foo = new MyVeryLongGenericTypeName<MyVeryLongClassName>(...);
4. Continue to use good variable naming conventions with Var and realize that Var is still strongly typed. You don't just throw out all your good practices becuase you've learned something new.

I'm kind of going out on a limb with this to try and make something positive come out of this thread. Is there anything else? Can we make these better? Do some of these not belong?
 
Last edited:
The code snippet you use in point 2 is more to do with anonymous types than generics, from what I have seen I would tend to stay clear of them in general anyway.
Using var with generics doesn't seem to be too bad of an idea and can remove a level of duplication that can result in easy mistakes later
C#:
//following requires the type to be specified twice, if int needs to be changed to long
//for example I need to change it in two locations
MyShortName<int> foo = new MyShortName<int>();

//only declare the type once
var foo = new MyShortName<int>();
 
A good point about generics and very pragmatic.

I fixed my post above. I meant to write 'anonymous' as that's what marble_eater was talking about, but I must have had generics on the brain while typing. sorry about the confusion.
 
Back
Top