Implicitly typed local variables introduced in C# 3.0 specification is very cool. Those who used VB and some other scripting languages are familiar with untyped variables and other who used VC++ and Delphi will remember the Variant type. But implicitly typed variables are different in C# 3.0. For example in VB actual type is determined at runtime and that is true for the Variant type too,but the actual type of the implicitly typed local variables are determined during compile time which eliminates lots of headache. C# 3.0 specification introduces "var" keyword to define an implicitly typed local variable. For example
public void SomeMethod()
{
//int x = 12;
var x = 12;
//double y = 12.0;
var y = 12.0;
//string z = "Sample string";
var z = "Sample string";
//int[] k = new int[]{1,2,3,4};
var k = new [] {1,2,3,4};
}
Returning back to the original issue, using implicitly typed local variables saves lots of coding time and may be considered as a must for LINQ powered C# code. But do not forget that every piece of code may be debugged or reviewed by another person and by you some time later which brings code quality issues into scene. Readability is one important sign of the code quality and in some cases and depending on your coding practices using implicitly typed local variables may decrease your code quality as a result of difficult to read/review code. The key point here is how we review a piece of text as an average human. From my personal experience I can say that
- We tend to anchor to the headings and try to understand the details backreferencing the heading
- We may need short descriptions or walk throughs before we start understanding a complex issue
- Not to get lost in a long text we tend to summarize what we have understood so far
- When we finish practicing the text we try to infer a result from what we have highlighted in previous steps
- After inferring a result we can start to invent our own understanding of the subject
I think that scheme is applicable to debugging and code review practice. Knowing these we, as software developers, should avoid practices which may turn our code to a nightmare for other developers. I think if you
- Use meaningfull names for your classes, methods and variables. Every code entity, be it a class, a varible or a method , should mimic its purpose of existence by its name if possible.
- Write atomic methods. I mean writing methods that perform only a single well defined task.
- Comment your code well (Some developers tend to write more comments than the actual code, if you do this I suggest you to review your code you might be doing something wrong or incomplete)
- Keep the level of method chaining in a reasonable level
you shall use implicitly typed local variables without hesitation. But if you have readability problems with your code be carefull while using implicitly typed local variables, that will bring more complexity to your already hard to grasp code.
9dd11812-b175-4d07-8ca7-ad45c630ead6|1|4.0