-
1 February, 2010
Is the C# var keyword considered harmful?
Until very recently, all my projects at work were written in pure unmanaged C++. Now that we're starting sprinkle a little C# in the mix, some interesting issues have arisen.
Today's issue revolves around the use of the
varkeyword. It's a relatively new concept in C# and is a topic of great debate. Basically,varallows for local type inference when the compiler can determine what the variable type should be.Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.Thus, the following two declarations of
iare equivalent:var i = 10; // implicitly typed int i = 10; // explicitly typedThe var keyword is great because it solves one of my pet-peeves with C# and Java -- having to write type names twice:
MyType foo = new MyType();This is verbose and unnecessary.
varoptimizes for the lazy by reducing the number of characters that have to be typed. The fewer the characters, the shorter the line, the easier it is to read. See for yourself:MyCustomTypeWithAVeryLongName foo = new MyCustomTypeWithAVeryLongName(); var foo = new MyCustomTypeWithAVeryLongName();The debate still rages on and I doubt anyone will cave in until we come up with some coding guidelines. In the meantime, I will continue to propagate
varthroughout our codebase.Posted by J.P. Cummins ● Comments (4)
-
June 22, 2009
-
May 10, 2009
-
April 16, 2009
-
January 17, 2009
-
January 12, 2009
-
October 26, 2008
-
October 14, 2008
-
October 12, 2008
-
November 7, 2007
-
»