my solution for a typesafe indexer I've searched the web if there is a generic indexer in c# (4.0 / WPF) but could not find anything about it.

So I came up with my own solution and would like to share it with you. I hope to get some feedback on improvements.

public dynamic this[string attribute, Type type]
{
    get
    {
        try
        {
            return Convert.ChangeType(base.GetAttribute(attribute), type);
        }
        catch (Exception)
        {
            return this[attribute];
        }
    }
}


Short explanation of how i use it: my class derives from a generic class which again derives from XmlElement (WPF). The generic class offers a generic method to add XmlAttributes where their can be of any data type.

Here are some examples of usage:

    task.AddAttribute&lt;bool&gt;("boolAttrib");
    bool boolAttrib = false;
    boolAttrib = task["boolAttrib", boolAttrib.GetType()];

    task.AddAttribute&lt;DateTime&gt;("datetimeAttrib", new DateTime(2013, 11, 4));
    DateTime datetimeAttrib = new DateTime();
    datetimeAttrib = task["datetimeAttrib", datetimeAttrib.GetType()];


As there is no such thing as a generic indexer and the "out" keyword cant be used this was the only solution i came up to.

Any advice to improve it is highly appreciated! Thanks! :)
You can use generics if you don't insist on it being an indexer:

public T GetAttribute&lt;T&gt;(string attribute)
{
    return (T)base.GetAttribute(attribute);
}


I'm not so sure about the other things you're doing. Convert.ChangeType() could just hide errors in your code. If you want to change the type of something, you should know about it and do it explicitly, not try to hide it.

The same applies to your catch. You should never catch (Exception) in library code, handle only the exceptions you know about (in this case, most likely just InvalidCastException). And returning a value that might be the wrong type on failure? That seems dangerous to me as well.