Possible to create an implicit cast for an anonymous type to a dictionary?

Posted by Ralph on Stack Overflow See other posts from Stack Overflow or by Ralph
Published on 2011-01-08T01:46:35Z Indexed on 2011/01/08 1:53 UTC
Read the original article Hit count: 549

Filed under:
|
|

I wrote a method like this:

using AttrDict = System.Collections.Generic.Dictionary<string, object>;
using IAttrDict = System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, object>>;

static string HtmlTag(string tagName, string content = null, IAttrDict attrs = null)
{
    var sb = new StringBuilder("<");
    sb.Append(tagName);
    if(attrs != null)
        foreach (var attr in attrs)
            sb.AppendFormat(" {0}=\"{1}\"", attr.Key, attr.Value.ToString().EscapeQuotes());
    if (content != null) sb.AppendFormat(">{0}</{1}>", content, tagName);
    else sb.Append(" />");
    return sb.ToString();
}

Which you can call like

HtmlTag("div", "hello world", new AttrDict{{"class","green"}});

Not too bad. But what if I wanted to allow users to pass an anonymous type in place of the dict? Like

HtmlTag("div", "hello world", new {@class="green"});

Even better! I could write the overload easily, but the problem is I'm going to have about 50 functions like this, I don't want to overload each one of them. I was hoping I could just write an implicit cast to do the work for me...

public class AttrDict : Dictionary<string, object>
{
    public static implicit operator AttrDict(object obj)
    {
        // conversion from anonymous type to AttrDict here
    }
}

But C# simply won't allow it:

user-defined conversions to or from a base class are not allowed

So what can I do?

© Stack Overflow or respective owner

Related posts about c#

Related posts about syntax