Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Indexer Property Question

I have a class like this:

public class SomeClass
{
    private const string sessionKey = "__Privileges";
    public Dictionary<int, Privilege> Privileges
    {
        get
        {
            if (Session[sessionKey] == null)
            {
                Session[sessionKey] = new Dictionary<int, Privilege>();
            }

            return (Dictionary<int, Privilege>)Session[sessionKey];
        }
    }
}

Now, if Ido this...

var someClass = new SomeClass();
var p = someClass.Privileges[13];

... and there is no key 13, I will get an error like this:

The given key was not present in the dictionary.

I would like to have a property that can be accessed in the same way as above, but will return a default object in case of the absence of the key.

I tried creating an indexer property like this...

    public Privilege Privileges[int key]
    {
        get
        {
            try { return _privileges[key]; }
            catch { return new Privilege(); }
        }
    }

... but it looks like that's not a C# 2008 language feature.

How can I access the property in the same way, but get the default object if the key isn't present?

like image 531
Ronnie Overby Avatar asked Feb 27 '26 17:02

Ronnie Overby


2 Answers

C# does not supported named indexers, as you have discovered.

Have you considered using a regular method instead of an indexer property? Not every programming problem requires the use fancy syntax to solve. Yes, you could create your own IDictionary implementation with an aggregated dictionary and change the property access behavior - but is that really necessary for something that just fetches a value or returns a default?

I would add a method like this to your class:

protected Privilege GetPrivilege(int key)
{
    try { return _privileges[key]; }
    catch { return new Privilege(); }
}

or better yet, avoid exception handling as a flow control mechanism:

protected Privilege GetPrivilge( int key )
{
    Privilege priv;
    if( _privileges.TryGetValue( key, out priv ) )
        return priv;
    else
        return new Privilege();
}
like image 117
LBushkin Avatar answered Mar 02 '26 05:03

LBushkin


You'll have to define your own IDictionary-based class with an indexer that has the desired behavior, and return an instance of that, rather than the stock Dictionary class, in your property getter.

like image 32
Pavel Minaev Avatar answered Mar 02 '26 06:03

Pavel Minaev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!