1
\$\begingroup\$

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<bool>("boolAttrib");
    bool boolAttrib = false;
    boolAttrib = task["boolAttrib", boolAttrib.GetType()];

    task.AddAttribute<DateTime>("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! :)

\$\endgroup\$
3
\$\begingroup\$

You can use generics if you don't insist on it being an indexer:

public T GetAttribute<T>(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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.