I have a special type of dictionary. I'm not sure how to do this exactly, but I'm looking to make the get method virtual, but not the set method:
public TValue this[TKey key]
{
get { ... }
set { ... }
}
Is it possible and if so what is the correct combination?
You can't do that directly - you would need to add a separate method:
protected virtual TValue GetValue(TKey key) { ...}
public TValue this[TKey key]
{
get { return GetValue(key); }
set { ... }
}
Sorry... There is no syntax for doing this in C#, but you can do this instead.
public TValue this[TKey key]
{
get { return GetValue(key) }
set { ... }
}
protected virtual TValue GetValue(TKey key)
{
...
}
I might be misunderstanding something but if your Dictionary
is going to be readonly you have to implement a wrapper to ensure it is really readony (the dictionary's indexed property is not virtual so you can't override its behavior) in which case you can do the following:
public class ReadOnlyDictionary<TKey, TValue>
{
Dictionary<TKey, TValue> innerDictionary;
public virtual TValue this[TKey key]
{
get
{
return innerDictionary[key];
}
private set
{
innerDictionary[key] = value;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With