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?