tags:

views:

79

answers:

3

Is there any way to avoid the repetition of the type in this kind of declaration of a class member?

Dictionary<string, int> myDict = new Dictionary<string, int>();
+3  A: 

No, you can only use var for local variables. Basically you're stuck with the repetition, I'm afraid.

Eric Lippert has a great blog post on this.


Interesting point to note: Java performs implicit typing and type inference the other way round, based on what you're trying to assign to. That means this is legal:

// Note: This is Java, not C#!
class CollectionHelpers
{
    public static <T> List<T> newList() 
    {
        return new ArrayList<T>();
    }
}

// In another class (doesn't have to be static)
static List<String> names = CollectionHelpers.newList();
Jon Skeet
http://blogs.msdn.com/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx
280Z28
Deleted my un-answer. Thanks for correcting me.
Jon Galloway
+2  A: 

Sure - use VB.NET. ;)

myDict as New Dictionary(Of String, Integer)()
Mark Brackett
A: 

Though it's not directly relevant to the question, some people may be interested that you can do this in C#3 using collection initialisation:

var myDict = new Dictionary<string, int>()
{
     { "one", 1 },
     { "two", 2 },
     { "three", 3}
};
Dan Diplo
This is not possible for class members as asked by the op.
John Kraft
I just thought it might be useful for some people, regardless. Ho hum.
Dan Diplo
@Dan, the problem here is not the object initializer list. That feature is pretty awesome. :) The problem is you can't use the `var` keyword for a class member - replace it with the dictionary type and your post will be both interesting and correct. :)
280Z28