Notice: Trying to get property 'display_name' of non-object in /home/woolsto1/ on line 52

Implicitly Typed Variables

I was recently happily coding away and disregarding the green squiggly line that Resharper was trying to force down my throat. NB I am a Resharper advocate, but sometimes I just don't take notice of the prompts it gives me. Anyway, I decided to check what Resharper was telling me regarding my variable assignment and realised something I had not known before.

My code was a simple variable assignment.

ViewModelCustomer customer = new ViewModelCustomer()

Resharper's prompt was to "Use implicitly typed variable declaration". So I decided to research some best practice on assigning variables and it seems that Resharper was right. While there isn't any concrete coding conventions regarding this, most people share the same point of view. That is, if the assigned value (right side of the assignment) is obvious, then use implicit typing.

Here are some examples

// When the type of a variable is clear from the context, use var  
// in the declaration. 
var var1 = "This is clearly a string.";
var var2 = 27;
var var3 = Convert.ToInt32(Console.ReadLine());

// When the type of a variable is not clear from the context, use an 
// explicit type. 
int var4 = ExampleClass.ResultSoFar();

// Naming the following variable inputInt is misleading.  
// It is a string. 
var inputInt = Console.ReadLine();

Til next time...