Extended methods
We could’t add methods unless you use reflection etc, prior to C# 2008.(Though we can use visitor pattern here:)) Now we can do that using extended methods. It can be inside only static classes and this should be the first keyword of parameters.
for example:
static class TesterUtilClass
{
// Every Int32 now has a Foo() method…
public static void Foo(this int i)
{ Console.WriteLine(“{0} called the Foo() method.”, i); }
// …which has been overloaded to take a string!
public static void Foo(this int i, string msg)
{ Console.WriteLine(“{0} called Foo() and told me: {1}”, i, msg); }
}
Also it has direct access to ther classes. For example:
using System;
using System.Collections.Generic;
using System.Text;
namespace MyExtensionMethods
{
public class Car
{
public int Speed;
public int SpeedUp()
{
return ++Speed;
}
}
public static class CarExtensions
{
public static int SlowDown(this Car c)
{
return –c.Speed;
}
}
}
No comments yet.
Leave a comment
-
Recent
-
Links
-
Archives
- August 2009 (1)
- July 2009 (2)
- April 2009 (4)
- March 2009 (6)
- February 2009 (5)
- January 2009 (4)
- December 2008 (3)
- November 2008 (35)
- October 2008 (20)
-
Categories
-
RSS
Entries RSS
Comments RSS