This might be a good approach to your problem, if using the Name
to define equality makes
sense for MyClass
generally, and not just in this particular dictionary:
public class MyClass
{
public string Name { get; set; }
public override int GetHashCode()
{
return Name.GetHashCode();
}
public override bool Equals(object other)
{
return this.Name == ((MyClass)other).Name;
}
}
Then your dictionary is simply indexed by MyClass
objects. If you have an explicit string
instead of a MyClass
instance, you can get the dictionary's value like this:
dict[new MyClass { Name = "Foo" }]
You could also add a:
public static implicit operator MyClass(string s)
{
return new MyClass { Name = s };
}
And index like:
dict["Foo"]
Again, only do this if it makes sense for MyClass
generally, not just for use in this particular dictionary. If it's for this particular dictionary, try another solution.