C# 3.0 - Hair extensions for wanna-be rubyists
Metaprogramming and cool syntax aside, there is something in ruby that is quite sexy and will be available to the .NET world once C# 3.0 is out: Check out this sweet ruby code:
Or here (works within your Rails environment):
3.weeks.ago
While the first code snippet will iterate from 2 up to 5, the second will provide you the time 3 weeks in the past from this moment in time. **Now **this is something we can provide as well in C#. For that we will have extension methods. Those are simply static methods that due to their syntax will attach themselves to the object specified. This is best explained by the following example:
The trick is the **this **keyword in its umpteenth meaning: It specifies that the method (and this only works for methods) will be attached to the specified type. In other words, as soon as you reference the namespace in which the extension is defined, three methods will be added to your int definition. This is the same trick how bog standard arrays and collections suddenly know how to behave within LINQ expressions.
Btw, another thing shown off is the new way to initialize properties of a newly instantiated object. This is a true code-lines saver, since in this simple case it means that I do not have to inherit a constructor three times if I want to allow a developer using the class to instantiate it with relevant values in a one-liner. An effective enhancement, if there ever was one.
Let me show you the TimeSelector class to finalize this treat:
Btw, this cannot be used to open up the innards of a foreign type definition: The type to be extended is only visible through its public / internal face, respectively.
Now, in your code you can do this:
The second example was the ability to iterate between two integers. This is also an extension to the integer type and it usage will be simplified by the concise syntax that can be used for providing inline expressions. First comes the code that enables it:
This version not only allows you to iterate up and down, but also defines an overload where you can specify your own stepping in the form of a lambda expression.
This stuff is used as such:
Sadly, the usage is not quite as cool as in the Ruby version, yet we have another way to express concise code. I can’t wait for nice extension libraries that will provide extensions to well known objects for given scenarios. I’ll probably start my own. If anyone has a nice idea that should find its way in the RF extension library, let me know.