The cost of creating Expression Trees

First, merry xmas etc. etc.. Second – expression trees. I just wanted to post a short blog about the actual cost of creating trees that can be illustrated by comparing the following two code samples: - See the difference? Rather than creating the expression inline of the for loop (Sample A), we create it once … Continue reading The cost of creating Expression Trees


Performance or readability with Expression Trees in C#

I was fumbling around trying to create some expression trees on Friday and was working through some stuff with a colleague of mine (someone who actually knows how to do it better than me!) and I got to thinking about the characteristics of different ways of doing the same things in C# with respect to … Continue reading Performance or readability with Expression Trees in C#

VS2010 Professional Review Part 2 – Dynamic Typing in C#4.0

Visual Studio 2010 comes with the next version of C# – version 4.0. The most controversial feature of this version seems to be the dynamic typing features that are built on top of the DLR (also part of the .NET 4). No, that’s not the Docklands Light Railway – it’s actually the Dynamic Language Runtime. The DLR is a new layer that sits on top of the Common Language Runtime (CLR) in .NET and provides some of the sorts of features available in existing dynamic languages (Python, Ruby) in existing CLR languages such as C# and VB as well as some of the newer .NET languages that are appearing. My (hugely limited) understanding of dynamic language are that they are primarily weakly typed languages i.e. little or no compile-time checking that e.g. you are accessing properties that exist or not etc.. Think how in JavaScript you can simply do something like assign a value to a property without having explicitly declared that property first etc.. In some languages, like Ruby, this is a fundamental part of the language and you can do things in those languages that look positively weird to a C# coder the first time you see them. So, what is dynamic typing in the C# sense? Something like this (albeit a contrived example, as usual). Here are two classes, Employee and Person. They have nothing in relation in terms of class hierarchies: class Employee { public string Name { get; set; } public int Age { get; set; } public string Department { get; set; } } class Person { public string Name { get; set; } public Gender Gender { get; set; } public int Age { get; set; } } Suppose we wanted to print to the Console the Name and Age of all Persons and all Employees. We would probably write two methods which takes in either an Employee or a Person, which would print the Name and Age of either a Person or an Employee and let the compiler choose which method to call depending on the type of object we’re dealing with. Or we might have a single method which does an if / then statement on the type (ugly :-). Or maybe we’d have a single method which used reflection to get the two common properties out of these types and print the details: static void PrintDetails(object detailsContainer) { object Name = detailsContainer.GetType().GetProperty ("Name").GetValue (detailsContainer, null); object Age = detailsContainer.GetType().GetProperty("Age").GetValue(detailsContainer, null); System.Console.WriteLine("{0} is {1} years old.", Name, Age); } Obviously, this is weakly typed – we’re passing in objects. At first glance, this is completely against what most C# coders have been taught to do. But consider – in some ways this is nicer than e.g. having two separate methods which do 99% the same thing – it’s easier to see what’s going on i.e. a single method which prints out the details of the object to the console rather than two methods which at first glance do the same thing. But the problems are: - Weak typing. Let’s leave this discussion for later on… The syntax to get the properties is ugly. Let’s deal with this now 🙂 Reflection is Ugly! Using reflection to get the value of a property isn’t hard to do in .NET, but it is a little strange to look at. Get the Type of the object you want to interrogate e.g. MyObject.GetType (); Get the PropertyInfo of the Property that you want e.g. MyType.GetProperty (“ThePropertyIWant"); Get the Value from the PropertyInfo given a particular object of that type e.g. MyProperty.GetValue (MyObject, null); So that’s a chain of three method calls to get any given property – at a glance, it’s all a bit "weird” to see what’s going on. Here’s how we would write the same PrintDetails method in C# using Dynamic typing: static void PrintDetails(dynamic detailsContainer) { System.Console.WriteLine("{0} is {1} years old.", detailsContainer.Name, detailsContainer.Age); } The main difference is the use of the “dynamic” type instead of “object” as the type of the method parameter. “dynamic” is a new type in C# which is in reality just plain old object. But it tells the compiler to not check any method invocations or property accessors until runtime, I presume using reflection (and you therefore get no intellisense when manipulating dynamic objects). So it’s no more or less weakly type than the reflection-based example, just a whole lot easier to read. You can cast any type as Dynamic and then do what you want with it – but you can of course get this “wrong” e.g. if I called a property or method that did not exist, I’d get a runtime error – just like you would with reflection (Mike Taulty has a good blog posting about resolution of overloaded methods using dynamic types and overloads). And just to clarify – dynamic is NOT the same as var! Dynamic is a 100% weakly typed object, you don’t even get the Object methods like ToString() and GetType on them (which every type has). Var is a always strongly typed object, even if it’s an anonymous type. Static versus Dynamic Typing Coming from a C# or C++ background, you might be wondering “why do we want features like this? Isn’t statically typing better than dynamic typing?”. Well, the impression I get from some of the interviews with people involved in the development and evolution of .NET is that they see C# and VB .NET becoming more of a hybrid language in the future, offering “best of breed” features from static and dynamic languages, just as in C# 3 they took declarative features from e.g. SQL which became LINQ and merged them with imperative language features like for loops. So, I think the answer to “is dynamic typing a good thing” is something like “yes, in its right place”. I wouldn’t expect us to chuck interfaces and class hierarchies etc. out of the window just because we can – but dynamic typing can be used in a few places in C# to make our lives a lot easier (and more readable!). Here are some examples: - Making code more readable by hiding Reflection. Talking of reflection, a lot of the time (always?) you will be able to avoid using reflection-style calls to get properties and methods and simply use the dynamic features in C# 4 instead. Interacting with dynamic languages. You can already have C# and VB .NET classes talk to one another, because they are both built on .NET. However, there are now some languages cropping up in the .NET world such as IronPython and IronRuby (I think?) which are .NET versions of Python and Ruby. So, in order to interact from the C# world with .NET assemblies written in those languages, you need to have support for dynamic typing in C#. Talking to COM libraries. There are some great examples on the Internet showing how much easier it is to interact with COM methods using dynamic typing than using Reflection. If you’ve ever done COM interop, such as Excel or Word document manipulation, you’ll know that this is a nightmare – using the dynamic keyword makes your code a lot more readable! This is also especially useful when interacting with e.g. JavaScript in Silverlight. However, there’s also a risk that people stop using "proper” static typing concepts such as interfaces and class hierarchies etc. simply because they cannot be bothered with it and using dynamic is “easier”. I’m not saying that this approach is something out of the “dark side” – I’m sure that there are times where it’ll be a real timesaver. And, provided you’re doing lots of good unit tests, you can probably get away with dynamic typing when required – but it’s not an excuse for breaking OO rules! If you want to find out more about dynamic, there are some decent videos on Channel9 and MSDN – there’s one in particular by Anders Heijlsberg who goes through the feature in great depth – worth checking out.