The product of a web developer with a little too much caffeine

Anonymous Types – Dynamic Programming With C#

with 15 comments

In a previous post I discussed trying to work with Anonymous types in .NET. I had included some code for working with those types to try and make it easier to pass your information around inside your projects.

Essentially, it was a wrapper for Reflection that allowed you to access properties by providing the correct type and property name. It would keep the instance of the Anonymous type in memory so it could work directly with the object.

You may have noticed that there was .Get() functions, but no .Set() function. Why is that?

You may have never noticed this before, but all of the properties in an Anonymous type are read-only. Most of the time you aren’t going to make changes to those values anyways, but if you can’t assign the value of a property in one pass, then it’s a bummer.

For fun, I took a little time to write another version of AnonymousType. This one is a lot more flexible than the one before, but you aren’t really using C# the way it was intended to be. Instead of using reflection you’re using a Dictionary, specifically with strings (for the property names) and objects (for the values).

You create objects the same way as before, but now you have access to a few more features and functions.

//Creating Instances of AnonymousType
//Create a using an Anonymous type
AnonymousType type = AnonymousType.Create(new {
  name = "Jim",
  age = 40
  //method = ()=> { Console.WriteLine(); } // still doesn't work here

//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 Using Methods
//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 Multiple Properties
//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);

Again, this is breaking away from the way C# was intended to be used, so be careful how much you make use of it. For the most part you’re going to want to create your own classes to hold this information, but while working with Anonymous types, this is a quick and easy way to pass your information around.

Stay tuned for version three (something really cool!)

Source Code

Download AnonymousType.Remix.cs


Written by hugoware

May 29, 2009 at 2:44 am

15 Responses

Subscribe to comments with RSS.

  1. Anonymous Types – Help C# Pretend to be Javascript « Yet Another WebDev Blog…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…


    May 29, 2009 at 4:40 am

  2. This is freakin ace. Thanks so much

    sacha barber

    June 24, 2009 at 8:25 am

  3. I think the C# 4.0 Dynamics will make your Anonymous type more interesting.

    Michael Brown

    July 7, 2009 at 12:34 pm

    • It will certainly make it cleaner – This method relies a lot on strings so it can break easily.

      The dynamic option will be a much better alternative when it arrives 🙂


      July 7, 2009 at 12:59 pm

  4. You should try doing this:

    public static T CBE(this T anonymous)
    return anonymous;

    var anonymous = new { name = “name” };
    var noMoreAnonymous = anonymous.CBE();



    July 11, 2009 at 3:32 am

    • I’m assuming you mean have a function that casts your type to another anonymous type. That works if you keep your variable in the same scope – If you leave the scope of that function then you have no way of knowing what the type is anymore.

      Essentially, you could do just…

      var m = new { name = “name” };
      var p = m;

      This was just used to help move an Anonymous type in and out of different scopes.

      I’ve seen other people do this before…

      public static T CastAs(object value, T format) {
      return (T)anonymous;

      var m = new { name = “m” };
      var p = CastAs(m, new { name = default(string) });

      Which works regardless of scope.

      Thanks for the comment!


      July 11, 2009 at 9:09 am

  5. […] This post was Twitted by mgroves […]

    Twitted by mgroves

    July 22, 2009 at 4:04 pm

  6. Very nice, thanks for sharing (and thanks Sacha for posting on your blog).
    Using the dynamic type in C# 4.0 will indeed make it look cleaner but it won’t save things breaking since there is no compile time checking. Plus, your current implementation will run faster than a dynamic object.


    July 24, 2009 at 6:13 am

  7. […] Anonymous Types (Sorta MVC related…) […]

  8. […] I use a lot of Models in my projects now. I used to suggest that you pass around objects using a wrapper for anonymous types but I’ve found that if you plan to move it from a Controller to a View or from a View to a […]

  9. […] now I’m working on my own driver to talk to Mongo that heavily relies on my AnonymousType code (anybody remember that old stuff?). It is still early on in the project so if you’re interested in helping feel free to contact […]

  10. […] creator of CSMongo and jLinq has created a class called AnonymousType that will allow you to persist an anonymous type beyond the scope of the method that creates that object.  In other words he has process that will allow to define […]

  11. […] idea regarding a class AnonymousType that could persist values from an anonymous object.  The AnonymousType, created by Hugo Benocci models an individual object.  In a sense this is a hyper-charged […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: