Extension methods a feature of C# 3.0
Someone said recently that they thought extensions methods required a new CLR.
Extension methods are a new feature in .NET 3.5 (C#3/VB9) that let you appear to "spot weld" new methods on to existing classes. If you think that the "string" object needs a new method, you can just add it and call it on instance variables.
Here's an example. Note that the IntHelper35 class below defines a new method for integers called DoubleThenAdd. Now, I can do things like 2.DoubleThenAdd(2). See how the method directly "hangs off" of the integer 2? It's the "this" keyword appearing before the first parameter that makes this magic work. But is it really magic? Did it require a change to the CLR, or just a really smart compiler?
Let's do some experimenting and see if we can figure it out for ourselves.
Extension methods a feature of C# 3.0 which gives us the capability of adding our own methods to existing Types without creating a new derived class.Extension Method's Are Special Static Method's which act like instance methods on extended types.
using System;
namespace vmc
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(2.DoubleThenAdd(3));
Console.WriteLine(IntHelper20.DoubleThenAdd(2, 3));
Console.ReadLine();
}
}
public static class IntHelper20
{
public static int DoubleThenAdd(int myInt, int x)
{
return myInt + (2 * x);
}
}
public static class IntHelper35
{
public static int DoubleThenAdd(this int myInt, int x)
{
return myInt + (2 * x);
}
}
}
This Example will create a Extension Method on an String Type to Convert a String to an Integer.
Example :
using System;
namespace ExtensionDemo
{
static class StringExtension
{
public static int ToInteger(this string val)
{
return Convert.ToInt32(val);
}
}
}
0 comments:
Post a Comment