2

I would like to create a dynamic class doing with the following:

  1. I have a dictionary where the keys are integers and the values are strings.

    Dictionary<int, string> PropertyNames =  new Dictionary<int, string>();
    PropertyNames.Add(2, "PropertyName1");
    PropertyNames.Add(3, "PropertyName2");
    PropertyNames.Add(5, "PropertyName3");
    PropertyNames.Add(7, "PropertyName4");
    PropertyNames.Add(11,"PropertyName5");
    
  2. I would like to pass this dictionary into a class constructor which builds Properties into the class instance. And suppose I would like to have both get and set functionality for each of these properties. e.g.:

    MyDynamicClass Props = new MyDynamicClass( PropertyNames );
    Console.WriteLine(Props.PropertyName1);
    Console.WriteLine(Props.PropertyName2);
    Console.WriteLine(Props.PropertyName3);
    Props.PropertyName4 = 13;
    Props.PropertyName5 = new byte[17];
    

I am having trouble understanding DLR.

Maelstrom Yamato
  • 167
  • 1
  • 2
  • 7
  • 3
    See this article, I think this will help: http://stackoverflow.com/questions/2974008/adding-unknown-at-design-time-properties-to-an-expandoobject – Glenn Ferrie Mar 12 '13 at 01:16
  • 1
    You're basically describing the `ExpandoObject`. Check it out: http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx – Sorax Mar 12 '13 at 01:24
  • Oh okay, I think that is straightforward enough. I never knew about ExpandoObject. – Maelstrom Yamato Mar 12 '13 at 01:36
  • 1
    Just out of curiousity, would anyone know why MSFT decided to name the class ExpandoObject instead of ExpandObject? It seems like a typo. – Maelstrom Yamato Mar 12 '13 at 01:37
  • 1
    Just FYI, you are discarding almost all compile-time checks and sacrificing performance when you use such types as ExpandoObject or DynamicObject. – Anton Tykhyy Mar 12 '13 at 03:05
  • @AntonTykhyy Thank you for letting me know about the performance penalty. This might be a deal breaker for me since I do have timing requirements. – Maelstrom Yamato Mar 14 '13 at 13:53

1 Answers1

1

The DynamicObject class seems to be what you want. In fact the documentation shows how to do exactly what you asked. Reproduced here in a stripped down version for brevity:

public class DynamicDictionary : DynamicObject
{
    Dictionary<string, object> dictionary = new Dictionary<string, object>();

    public int Count
    {
        get { return dictionary.Count; }
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        string name = binder.Name.ToLower();
        return dictionary.TryGetValue(name, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        dictionary[binder.Name.ToLower()] = value;
        return true;
    }
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331