Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Indexer properties - Any way to virtualize the get and not the set method?

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?

like image 227
myermian Avatar asked Jul 11 '11 19:07

myermian


3 Answers

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 { ... }
}
like image 180
Marc Gravell Avatar answered Nov 15 '22 10:11

Marc Gravell


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)
{
   ...
}
like image 38
agent-j Avatar answered Nov 15 '22 12:11

agent-j


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;
        }
    }
}
like image 38
InBetween Avatar answered Nov 15 '22 10:11

InBetween