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…


  • agar cheats says:

    Thanks on your marvelous posting! I genuinely enjoyed reading
    it, you will be a great author. I will be sure to
    bookmark your blog and will eventually come
    back very soon. I want to encourage that you continue your
    great work, have a nice afternoon!

  • Hello would you mind letting me know which web host you’re working with?

    I’ve loaded your blog in 3 different internet browsers
    and I must say this blog loads a lot quicker then most.
    Can you suggest a good hosting provider at a honest price?

    Many thanks, I appreciate it!

Leave a Reply

Your email address will not be published. Required fields are marked *