Hugoware

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

Posts Tagged ‘Reflection

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

Simplify Using Anonymous Types

with 7 comments

New Version Available:Check out this post about the AnonymousType class Remixed!.

When you’re using ASP.NET MVC you pass information from the Controller to the View. Your information is found in the ViewDataDictionary where you can cast the info back into whatever form it originally was. Additionally, you can even specify a model type for the page so that no casting is required to access your information.

It may be a little inconvenient, but it’s not bad. This just means you need to either define the class in advance or limit yourself to simple values.

If you’re writing LINQ queries and creating anonymous types then you’re in a tougher situation. I’ve seen people try and come up with solutions for accessing an anonymous type after its been created, but nothing seemed all that intuitive.

In the next version of C# we’re going to see the new dynamic declaration which will most likely solve this problem. For now, Reflection is about the only way you solve this issue.

On a recent project I got a little tired of trying to manually do this each time. I ended up writing a wrapper class (included at the end of the post). The example below shows how you can use this class AnonymousType.

//Controller
//==================
this.ViewData["details"] = new {
  name = "Jim",
  age = 30
};


//View
//==================
AnonymousType details = new AnonymousType(this.ViewData["details"]);

//access properties
string name = details.Get<string>("name");
int age = details.Get<int>("age");

//supply a default type in case the property doesn't exist
bool fake = details.Get<bool>("someFakeProperty", false);

//Use the properties by name - maps to the argument name
details.Use((string name, int age) => { 
  Console.WriteLine("{0} is {1} years old", name, age);
});

//An wrong property name (wrong type or incorrect case) will cause an error
details.Use((int NAME) => { /* Error! */ });

It’s really just Reflection, but it streamlines using unknown types inside of a View.

Now, if you are thinking “What about methods? or Fields?” then you’re like me. Now, if your second thought was “Well wait, if it has methods then it’s a defined class, we should just cast it instead.”, then you’re much smarter than me. Unfortunately, I spent an hour or so writing ComplexAnonymousType that would call methods (even match correct signatures), access fields, the works… then to realize how much of a wasted effort it was. 🙂

Anyways, try it out if interested. Let me know what you think!

Don’t forget! Reflection is slower than the normal means of accessing properties. While the time spent is negligible in small amounts, if you’re going to be using this code below with a lot of items, it may be wiser to define a class instead.

Source Code

Download AnonymousType.cs

New Version Available:Check out this post about the AnonymousType class Remixed!.

.

Written by hugoware

May 13, 2009 at 11:41 am