1

Does ExpandoObject have any convenience factory methods? Something like, I don't know,

dynamic disney = new ExpandoObject("First", "Donald", "Last", "Duck");
William Jockusch
  • 26,513
  • 49
  • 182
  • 323
  • Did you try `dynamic disney = new ExpandoObject {First="Donald", Last="Duck"};`? I am curious if it's going to work (I don't have access to my Windows workstation at the moment to check it). – Sergey Kalinichenko Apr 26 '16 at 11:08

1 Answers1

5

Nope, there isn't, but you can write it in minutes. :) Here you go:

C#

class Program
{
    static void Main(string[] args)
    {
        dynamic ex = ExpandoFactory.Create("First", "Donald", "Last", "Duck");
        Console.WriteLine(ex.First);
        Console.WriteLine(ex.Last);
    }
}

static class ExpandoFactory
{
    internal static ExpandoObject Create(params string[] items)
    {
        //safety checks omitted for brevity
        IDictionary<string, object> result = new ExpandoObject();
        for (int i = 0; i < items.Length; i+=2)
        {
            result[items[i]] = items[i + 1];
        }
        return result as ExpandoObject;
    }
}

Of course, you should check the cardinality of the array beforehand. I hope this helps.

df_
  • 149
  • 4
  • 11