JoelFan
JoelFan

Reputation: 38714

avoid type repetition in class member initializer?

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>();

Upvotes: 1

Views: 155

Answers (3)

Dan Diplo
Dan Diplo

Reputation: 25349

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}
};

Upvotes: -2

Mark Brackett
Mark Brackett

Reputation: 85665

Sure - use VB.NET. ;)

myDict as New Dictionary(Of String, Integer)()

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502536

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();

Upvotes: 3

Related Questions