No, it will not. It has no intrinsic knowledge of what a Dictionary
is. For the compiler, it's just a normal class, so it doesn't know it could reuse the instance in this particular case.
This would be the proper way to do this:
public class Something
{
private static readonly Dictionary<string, string> _dict = new Dictionary<string, string>
{
{"a", "x"},
{"b", "y"}
}
private string Parse(string s)
{
return _dict[s];
}
}
This approach works because you know what the object does and you also know it's never modified.
Remember the following syntax:
var dict = new Dictionary<string, string>
{
{"a", "x"},
{"b", "y"}
}
Is just syntactic sugar for this:
var dict = new Dictionary<string, string>();
dict.Add("a", "x");
dict.Add("b", "y");
The only requirement to make this work with any class, is for the class to
- Implement
IEnumerable
- Have a public
Add
method.
You suggested to use a switch
statement, but the Dictionary
approach can be more flexible. Consider for instance you could want to use a different equality comparer (like StringComparer.OrdinalIgnoreCase
). It's better to let the Dictionary
handle this using the proper comparer than using something like switch(value.ToLowerInvariant())
.