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>();
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>();
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();
Sure - use VB.NET. ;)
myDict as New Dictionary(Of String, Integer)()
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}
};