C# 4.0

Just read an interesting post on the new stuff coming in .NET 4.0, specifically in C#. Here’s some quick samples:

“Dynamic” objects

Let’s say we have some sort of untyped object, be it from Javascript, or COM, or Ruby, or whatever. Normally to be able to use it in .NET you’d have to do some amount of reflection to determine what methods and properties were available, followed by a Type.InvokeMember call. Not anymore!

Dynamic objects
1
2
3
//some method that returns an "object"
dynamic calculator = GetCalculator();
int result = calculator.Add(4, 6);

With the example above, .NET reflects the object, determines if there’s a method that’s called “Add”, takes two ints as method arguments, and returns an int. If it doesn’t find one it’ll throw a runtime error.

Optional & Named Parameters

Forget all that method overloading we used to have to do, now we can specify optional parameters, AND define which of the optional parameters we want to pass in!

Optional and Named Parameters
1
2
3
4
5
6
7
8
9
10
//method that only really requires "path" as a parameter
public void LoadSomeFile(string path, Encoding encoding = null,
  int bufferSize = 1024)
{
//code, whatever
}
//method call examples
LoadSomeFile("c:/dev/test.html");
LoadSomeFile("c:/dev/test.html", Encoding.UTF8);
LoadSomeFile("c:/dev/test.html", bufferSize: 512);

Comments