C# 4.0

With the fourth iteration of the language, Microsoft tried to simplify the versioning confusion it created over the previous few releases by incrementing the version of every component to 4.0.

C# 4.0

C# 4.0 brings more dynamic functionality into the language and continues the work of making C# a very powerful, yet agile language. Some of the features added are primarily to make interoperation with native platform code easier. Things such as covariance, contra variance, and optional parameters, simplify the process of doing things, calling the interop assemblies for interacting with Microsoft Word, for example. All in all, not very earth-shaking stuff, at least for your average day-to-day developer.

However, with a new keyword that was added, dynamic, C# takes a step closer to becoming a very dynamic language; or at the very minimum, inheriting many of the qualities of dynamic languages. Remember when generics were introduced, if you had a bare type parameter (that is, with no type constraints), it was treated as an object. The compiler had no additional information about what kind of methods and properties the type had access to at runtime, and as such you could only interact with it as an object.

In C# 4.0, you now have a way of writing code that can bind to the correct properties and methods at runtime. The following is a simple example:

dynamic o = GetAString() ;

string s = o.Substring(2, 3);

Tip

If you are migrating a project from an earlier version of the framework, make sure you add a reference to Microsoft.CSharp.dll, when using dynamic programming. You will receive a compilation error if this is not present.

In this hypothetical scenario, you have a method that returns a string. The variable that is receiving the return value of the GetAString() method is marked with the dynamic keyword. This means that every property and method that you call on that object will be dynamically evaluated at runtime. This lets C# easily interop with dynamic languages, such as IronPython and IronRuby, in addition to your own custom dynamic types.

Does this mean that C# is no longer statically typed? No, quite the opposite; C# is still statically typed, just that in this case you have told the compiler to handle this code differently. It does this by rewriting your dynamic code to use the Dynamic Language Runtime (DLR), which actually compiles out expression trees of your code that are evaluated at runtime.

You can easily create your own dynamic objects by inheriting from the built-in class called DynamicObject as follows:

public class Bag : DynamicObject
{
    private Dictionary<string, object> members = new Dictionary<string, object>();

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return members.Keys;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        return members.TryGetValue(binder.Name, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        members[binder.Name] = value;
        return true;
    }
}

In this simple example, we inherit from DynamicObject and override a few methods to get and set the member value. These values are stored internally in a dictionary so that you can pull out the correct value when the DLR asks for it. Using this class is very reminiscent of how flexible objects are in JavaScript. Look at the following code:

dynamic bag = new Bag();

bag.Name = "Joel";
bag.Age = 31;
bag.CalcDoubleAge = new Func<int>(() => bag.Age * 2);

Console.WriteLine(bag.CalcDoubleAge());

If you need to store a new value, simply set the property. And if you want to define a new method, you can use a delegate as the value for the member. Of course, you must realize that this will not be as fast as having a regular statically typed class, every value must be looked up at runtime, and because values are stored as objects internally, any value type will be boxed. But sometimes those drawbacks are completely acceptable, especially when it can simplify your code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.187.233