Project Description
AnonymousType is a class that allows you to wrap any object, including anonymous types, and have full access to properties and methods. You can use lambdas to map to property names and have access to intellisense as well.
For additional information
visit my blog
Creating A New Anonymous Type
Create a new anonymous type and map it directly into an AnonymousType class so it can be passed around in different areas!
//Create a using an Anonymous type
AnonymousType type = AnonymousType.Create(new {
name = "Jim",
age = 40
//Can't create lambdas inline with an anonymous type, but
//you can add them after the fact...
//method = ()=> { Console.WriteLine(); } // won't work
});
//or an empty AnonymousType
AnonymousType empty = new AnonymousType();
//or even an existing object
var something = new {
name = "Mark",
age = 50
};
AnonymousType another = new AnonymousType(something);
Creating And Calling Methods
If you need to call a method -- or even define a new method inline -- you can use the
SetMethod and
Call functions!
//append methods and call them
another.SetMethod("print", (string name, int age, bool admin) => {
Console.WriteLine("{0} :: {1} :: {2}", name, age, admin);
});
another.Call("print", "Mark", 40, false);
//append a method with a return value
another.SetMethod("add", (int a, int b) => {
return a + b;
});
int result = empty.Call<int>("add", 5, 10);
Working With More Than One Property At A Time
Some times you need to work with a set of properties -- Instead of accessing each item with a
Get call you can use the
With method to create a Lambda with the name of your property cast into the correct type! Now you have intellisense with your dynamic object!
//add properties and work with them
//===(NOTE: a better way is shown below)===
another.Set("list", new List<string>());
another.Get<List<string>>("list").Add("String 1");
another.Get<List<string>>("list").Add("String 2");
another.Get<List<string>>("list").Add("String 3");
//or use it an easier way
another.With((List<string> list) => {
list.Add("String 4");
list.Add("String 5");
list.Add("String 6");
});
//you can work with more than one type
another.With((string name, int age) => {
Console.Write("{0} :: {1}", name, age);
});