Home > OS >  Create an anonymous type dynamically
Create an anonymous type dynamically

Time:08-21

I am able to creaate a dynamic type at edittime

var orderFields = new
                {
                    legs = new[] {
                        new { 
                             instrumenttype = "Equity Option", 
                             symbol = "SPY   221021C00422000",
                             quantity = "1",
                             action = "Buy to Open"
                        },
                        new {
                             instrumenttype = "Equity Option",
                             symbol = "SPY   221021C00420000",
                             quantity = "1",
                             action = "Sell to Open"
                        },
                    }
                };

However, I don't know how many of these there will be at runtime:

new { 
         instrumenttype = "Equity Option", 
         symbol = "SPY   221021C00422000",
         quantity = "1",
         action = "Buy to Open"
    },

The source of the instances could be a List<DataRow>, or List<Struct>

I am able to do this at edittime ok, but don't know how to fill in the rest at runtime:

var orderFields = new
                {
                    
                };

How do I create an anonymous type at runtime and add these to the legs []?

CodePudding user response:

Anonymous types are not anonymous at runtime. The compiler creates types.

There is a way to create new types at runtime, using reflection. Use TypeBuilder.CreateType for that.

Depending on your requirements, there may be other ways to achieve your goal. Look into the dynamic ExpandoObject. This is in essence a dictionary, but combined with the dynamic keyword, it behaves like a dynamic type.

CodePudding user response:

There is humor in programming! I literally laughed out loud when this worked, because I just dreamed this up and was shocked that it compiled at all, AND it actually works! LOL!

public class Leg
{
    public string instrumenttype { get; set; }
    public string symbol { get; set; }
    public string quantity { get; set; }
    public string action { get; set; }
}

var leg1 = new Leg { instrumenttype = "Equity Option", symbol = "SPY   221021C00422000", quantity = "1", action = "Buy to Open" };
var leg2 = new Leg { instrumenttype = "Equity Option", symbol = "SPY   221021C00420000", quantity = "1", action = "Sell to Open" };

var Legs = new Leg[2] { leg1, leg2 };

var orderFields = new
{
    Legs
};
  • Related