I want to explore reflection by playing with both reflection, anonymous types and dynamically typed things all at once! My goal is not to be confusing or anything, but it is to leave out the parts that are redundant.
So let’s get to it!
I sometimes find myself having a lot of data that I want to search through, it might be the same structure for each element and it might not, I can never assume that it’s the same structure though, because if I would, there would most certainly be a case where it differs.
Let’s assume that we have two anonymous types here:
var person =new{Name ="Filip", Surname ="Ekberg", Age =24};
var animal =new{Name ="Baloo", Breed ="Some breed", Age =14, Owner ="Filip"};
In my last post, I talked about the properties on anonymous types being read-only, the fact is that the entire anonymous object is read only, so even if I would say that it’s a dynamic anonymous type, I wouldn’t be able to specify new properties or methods on it.
Anyways! We have the above two objects that I want to search for something in, it might be the age, it might be a common string. So there are a few things that I got to figure out before I can start retrieving my results, here are the things we need to know:
How do we get all the properties from the object?
How do we get the value for the current property on the current object?
How do we get the type of the object, does it matter that it’s anonymous/dynamic?
Almost all of the above have been used here and there in my previous posts, but to answer them again:
How do we get all the properties from the object?
To get all the properties, we must first get the type, so we can retrieve all the properties for that type, like this:
obj.GetType().GetProperties()
How do we get the value for the current property on the current object?
To get the current value of the objects property you call GetValue like this, the second parameter is null because it’s not an array:
var value = property.GetValue(obj, null);
How do we get the type of the object, does it matter that it’s anonymous/dynamic?
When you’ve retrieved the value of the property, you get the type of the value by doing this:
value.GetType()
Now we have the basics and need to put every piece together so that we can search our objects, I want to have a method like this to find objects in a list with any property containing the Exact value that I pass:
My code that calls this method will look like this:
var person =new{Name ="Filip", Surname ="Ekberg", Age =24};
var animal =new{Name ="Baloo", Breed ="Some breed", Age =14, Owner ="Filip"};
var toLookup =new List<dynamic>{person, animal};
var found = Find("Filip", toLookup);
So what can the implementation look like? We can either solve it with LINQ or with a foreach.
My method will start out by only declaring a new list that we will put the found elements in and then I just return it to make everything build nicely:
IEnumerable<dynamic> Find(dynamic pattern, IEnumerable<dynamic> source) {
var found =new List<dynamic>();
// Implementation goes here....
return found; }
Now I need to iterate over my source-variable and for each item, I need to go through each property and see if the value matches the pattern input. I add the two nested foreach-loops like this:
foreach(var obj in source) { foreach(var property in obj.GetType().GetProperties()) { } }
It’s now iterating over each property on each object, you don’t want to move the GetType().GetProperties() outside the foreach-loop, since in our case the structure changes over each iteration. Now we’ve come to the final part, we need to get the value of the current property on the current object and see if the type matches the pattern type and then check if the value matches the pattern:
You might not want to use the equality operator in your case, if it’s a string you might want to check if the pattern is anywhere in the current value or something like that.
This is how my Find-method turned out:
IEnumerable<dynamic> Find(dynamic pattern, IEnumerable<dynamic> source) {
var found =new List<dynamic>(); foreach(var obj in source) { foreach(var property in obj.GetType().GetProperties()) {
var value = property.GetValue(obj, null);
In C# 3.0 something called anonymous types was introduced, this means that a certain context can have a type that is not defined anywhere except in that context. This has been seen a lot in LINQ-queries over the years. Here’s an example of an anonymous type:
If we hover the person-variable we should see something like this show up:
Having this anonymous type in our context means that we could write person.Name to get the value of the Name variable. One thing that is important when talking about anonymous types is that the variables are read only, which means that you cannot change Name after you’ve initialized the anonymous type.
I mentioned before that this has been seen a lot when using LINQ you might have seen code like this:
var persons =from person in context.Persons selectnew{ Name = person.Name, Age = person.Age};
This would as you might imagine give us a list of anonymous types where each type has a Name and Age property.
All this is pretty neat itself, but what happens when you want to use the anonymous type outside the context of where it was created and still maintain accessibility? The answer to this was introduced in .NET 4.0.
And the answer is dynamic!
Before we dig into what dynamic will help us with here, let’s take a look at how we can return an anonymous type from a method without the use of dynamic. Consider the following method:
object GetAnonymousType() {
var person =new{ Name ="Filip"}; return person; }
But if we debug the application and hover the person-variable, we will see this:
This is quite irritating, right? There’s a fun way to actually get the property value and that is by using reflection like this:
var person = GetAnonymousType();
var properties = person.GetType().GetProperties();
var name = properties.First(x => x.Name=="Name").GetValue(person);
This will actually give us what we want, but hey, this is quite ugly right? I am all about readable and clean code, now I am not telling you to pass around anonymous types everywhere, but now and then it can actually be usefull.
There’s actually just One thing that I need to change in the above code, and that is to set the return type to dynamic instead of object, like this:
dynamic GetAnonymousType() {
var person =new{ Name ="Filip"}; return person; }
I can now use this and successfully retreive my properties on this object:
var person = GetAnonymousType();
Console.WriteLine(person.Name);
This is what I call simple and readable code! Instead of having to add a new class, add each of the properties in the anonymous type to the new class and so forth, you can just use dynamic to get the stuff to work as you imagine it should!
However, even if we return it as a dynamic type, the properties are still read only!
I hope you found this interesting and if you have any thoughts please leave a comment below!
My last posts have been a lot about what you can do to explore the dynamic world in .NET and what it might be good for. But I think it’s time for some real fun with dynamic!
So go ahead and fire up Visual Studio, see to it that you got NuGet installed, now let’s get rocking!
The first thing you want to do is to create a new console application with any name of your choice, then I want you to go into:
This is the NuGet console, here you can do all kinds of neat stuff, we are going to use it to install IronPython into our project, so simply write the following in the console:
Install-Package IronPython
After 30 seconds to a minute or so, you should see something like this:
This means that IronPython was successfully added to our project! But wait a minute, what is IronPython? This is the definition of it according to Wikipedia:
IronPython is an implementation of the Python programming language targeting the .NET Framework and Mono.
A couple of lines below that something interesting is stated, have a look at this part:
IronPython is implemented on top of the Dynamic Language Runtime (DLR), a library running on top of the Common Language Infrastructure that provides dynamic typing and dynamic method dispatch, among other things, for dynamic languages. The DLR is part of the .NET Framework 4.0 and is also a part of trunk builds of Mono. The DLR can also be used as a library on older CLI implementations.
Hold your horses!
Let’s take a step back and think about what this means, basically it means that we can write Python code and have it interact with our code that we write in .NET! Let’s look at some code and see if this clears up a bit.
I’ve got a Python library that is somewhat going to be used for advance math-calculations and it looks like this:
class FEMathLibrary: def__init__(self): self.y=3 self.z=4
def add(self,a,b): return a + b + self.y + self.z
For those that don’t know Python programming, what this basically does is that it creates a class, gives it two properties ( y and z ) and then it has a method called add that takes two parameters when it’s called ( a and b ). Now, I’ve spent years and years optimizing this very advance mathematical operation and I don’t want to re-write it in .NET, that would take a lot of time and cost to much. It’s also worth mentioning that Python is a dynamically typed programming language and c# is a statically typed programming language.
I imported this file into my visual studio project and the project should now look somewhat like this:
You also need to change the property on the file that states that it will be copied to the output directory, the properties for the file should look like this:
Let’s dig into the C# code, shall we?
This is what I want to do ( in human understandable terms ):
Create a runtime that can run Python code
Tell the runtime to run my file
Create an instance of FEMathLibrary
Run the very advanced Add-function
Print the result
The only two things that you need to import are the following:
usingSystem; usingIronPython.Hosting;
IronPython.Hosting contains a lot of classes that we can use to help us achieve the above. One of these things being a class called Python that has a very interesting method on it called CreateRuntime, we can use that like this to actually create our runtime:
var runtime = Python.CreateRuntime();
The second thing on the list is to tell the runtime to load the file, this is done by using the method UseFile on the runtime-instance. We should now have something that looks pretty much like this:
var runtime = Python.CreateRuntime();
dynamic source = runtime.UseFile("FEMathLibrary.py");
Here’s what’s interesting, the source variable is dynamic! If this was python, we could write something like this:
So what about the C# version? How do we create the instance of FEMathLibrary? Our dynamic object is what will let us do this, we simply write the following to create an instance of FEMathLibrary:
var instance = source.FEMathLibrary();
The rest is pretty much the same thing! Here’s how it turned out:
var runtime = Python.CreateRuntime();
dynamic source = runtime.UseFile("FEMathLibrary.py");
dynamic instance = source.FEMathLibrary();
var result = instance.add(1, 2);
Console.WriteLine(result);
The result variable contains the value 10 and that’s also what is printed out to the console! As you might see this is pretty powerful, we could even use the variables inside the FEMathLibrary instance if we wanted.
So this is one way that you can make use of dynamic in your application, IronPython has more usage areas but that’s not something that I want to cover in this post.
In my previous post I talked about how you can extend the DynamicObject so that you can override TryInvokeMember and TryGetMember. However, these are not the only methods that you can override. I wanted to take a brief moment and talk about one of the other methods that you can override as well, this being TryInvoke.
According to MSDN this is the reason why you want to override TryInvoke:
Provides the implementation for operations that invoke an object. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as invoking an object or a delegate.
So whatever does this mean and how do you use it?
When we overrid TryInvokeMember that meant that we could call a method that actually was not implemented in our class like this: myDynamicObject.SomeMethodToIvoke(). In this case we assumed that SomeMethodToInvoke was a member of myDynamicObject.
So this leaves us with a method that lets us invoke something, that is not a member but an actual object, this means that we can invoke our object as if it were a method. We could pretty much write this:
dynamic db =new Database();
db(Operation.Refresh);
The operation-enum looks like this:
enum Operation { FullReset, Refresh, Update };
Without changing anything in the Database-class that was created in the previous post, we will get this exception “Cannot invoke a non-delegate type” but if we add the following and compile again, everything will work out nicely!
publicoverridebool TryInvoke(InvokeBinder binder, object[] args, outobject result) {
result =null;
returntrue; }
Exactly as I did with TryInvokeMember, I can get all information that I need out from the binder and args. In this case args will contain of one item with the value Refresh and if we add some more code here it could somewhat turn out like this:
publicoverridebool TryInvoke(InvokeBinder binder, object[] args, outobject result) {
result =null;
switch((Operation)args[0]) { case Operation.Refresh: // Refresh the context break; }
returntrue; }
Again, I am not saying this is what you should do, it’s just a way to demonstrate the different options you have when working with dynamic types in .NET.
If you have ever programmed in a dynamic programming language you know that you can pretty much ask for anything on any object, consider this code in any dynamic programming language:
var person =new Person();
person.Name="Filip";
person.Location="Gothenburg";
In the Person-structure used above, the property Location actually doesn’t exist, but in a dynamic programming language this is completely valid to do even if it doesn’t. You might wonder why you would ever want to be able to call on something that doesn’t exist; I will get back to that a bit further down this post.
First, let us take a look at how you would achieve something like this in C#!
Consider that we already have a class that is called “Database”, this class handles all communication with our data base or our data layer. To make my Database-class dynamic, I am going to extend it with DynamicObject. Extending with DynamicObject will allow me to override a lot of interesting methods, these two are the ones that are interesting to us now:
So what do these two methods actually allow us to do? TryGetMember will be invoked each time you try to access a member on the object, like a property or a field. TryInvokeMember will be invoked each time you try to invoke a method on the object.
If we take the first code sample from this post and compile it Visual Studio, we will get an error telling us that “Person does not contain a definition for Location” ( assuming that we have the same Person-structure here as well! ).
To avoid this, we say that the object that we are instantiating is dynamic, so in our case we have the following class defined:
The first parameter is used to get information about what the caller expects such as:
What name was used? ( Property name, Method name )
What return type is expected?
How many arguments did we pass along? ( Only for InvokeMemberBinder )
What are the argument names? ( Only for InvokeMemberBinder )
The second argument is used to set the return value and as for TryInvokeMember, we have another parameter as well, the actual arguments.
Both TryInvokeMember and TryGetMember returns a boolean that tell us if the operation succeeded or not. You might want to return false if you don’t support the property/method that was called.
So what can you do with this? Let’s take a look at some real code here!
When using the instance of our Database class I want to be able to do the following:
var products = db.Products.All();
I will not be doing any database code here, I just want to cover how to use the DynamicObject, so let’s take a look at that. First of all I override both TryInvokeMember and TryGetMember, the first method of these that will be called in the above statement is the TryGetMember.
In order to allow this fluent style of code I want me TryGetMember to look like this:
What I do here is that I have a property inside my Database class that is called “Table” which just holds the name of the current table that I am working with, then I return myself as a result and finally I return true which indicates that the call worked.
The above will allow me to write db.Products and this will return our Database class with the Table-name set to “Products”.
Now the easy part is over, the next step can be as complicated as you want since you have the binder-parameter, you can get information about the Name, Arguments and Return type. What I want to do is to check if the Name of the method that I want to invoke starts with “Select” then I can ( if I want ) later on check if it is SelectAll, SelectFirst, SelectRandom and so on.
With that out of the way, all I want to do is to set the result to whatever my select returns, in this example I will just set it to null for the sake of this example.
By using the above code, the following compiles and runs perfectly!
dynamic db =new Database();
db.Products.SelectAll();
If you debug this, you see that TryGetMember is first accessed, the SelectAll is invoked on the returned object which takes us to TryInvokeMember where it checks what kind of method we tried to invoke.
As you can see, this opens up a whole new world of dynamic usage! In my last post, I mentioned Simple.Data and that they made use of dynamic very well, their ORM works pretty much like this and is very neat for smaller applications.
I am not saying that everything should be dynamic, but once in a while it might actually be a product step to take this approach. Just take a look at Simple.Data and you’ll see what I mean.
Meanwhile I am planning and writing manuscript and code samples for my upcoming video series that will cover “Programming fundamentals using C#”, I thought it was time for a short post on some dynamic programming in C#!
So, for those that are completely new and haven’t yet checked out my videos on “C# 4.0 Using the Dynamic Keyword”, here’s a quick summary:
C# is not dynamically typed even though you can have dynamic types. It’s a statically typed dynamic type!
ExpandoObject is the object that you use with the dynamic keyword(contextual keyword) in order to add properties and methods dynamically.
Dynamics are evaluated at runtime
A typical dynamic setup that creates a dynamic object and adds a static amount of properties might look like this:
dynamic person =new ExpandoObject();
person.Name="Filip";
person.Age=24;
What is interesting about the ExpandoObject is that it implements the interface:
IDictionary<string, Object>
So what this means is that if we cast the person-object to an IDictionary we will be able to do some really cool stuff with it. The same code above but re-written to make use of the dictionary instead could look like this:
dynamic person =new ExpandoObject();
var dictionary =(IDictionary<string, object>)person;
Now you might ask why this would ever be useful? In fact I first encountered this when Rob Conery threw together a part of Massive on stage on the Norwegian Developers Conference this summer. In his case he wanted to create an extension for an IDataReader which would give you a List instead of having to fight with the IDataReader.
So to make this as dynamic as possible, all the fields from the table was read, added with their corresponding values from the IDataReader into the dictionary, which made the whole thing very dynamic.
There are actually more ORMs(Simple.Data) out there that uses this approach, but I will get to that later on when I’ll cover DynamicObject!
This is how you add dynamic properties, but how about adding a method? It’s simple!
What you do is that you add a new key to the dictionary and the object should just be an action, like this:
dictionary.Add("Shout", new Action(()=>{ Console.WriteLine("Hellooo!!!");}));
person.Shout();
When calling the Shout-method it will print out “Hellooo!!!” in the Console.
I hope you had fun reading this and that you learned something new! Stay tuned for more posts!
This is my third screencast, talking about the dynamic keyword in C# 4.0. In this session I talk briefly about the dynamic keyword, where you might have seen it before and give some examples on how you can use it. I won’t go in to depth on the DRL, ExpandoObject or when/when not to use the Dynamic Keyword, that’s a whole other video.
As I stated in my last post I want to do short 8 – 15 minute videos scratching on the surface and then go in depth on the parts that most of you find interesting!
If you have any requests or questions regarding this or any other of my videos, don’t hesitate to leave a comment.
Filip Ekberg is a Senior Software Engineer working in the country with all the polar bears, author of a self-published C# programming book and overall in love with programming.
Check out my recently published book.C# Smorgasbord covers a vast variety of different technologies, patterns and best practices that any C# developer should master.
All printed copies include access to the e-book bundle (PDF, ePub and Mobi!).