Ebeworld’s Weblog

Trying to create

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;

    }

  }

}

Also using keyword also imports extension methods. Extension methods can work through classes
 static void Main(string[] args)
    {
      Console.WriteLine(“***** Extending an interface *****\n”);
      // Call IBasicMath members from MyCalc object.
      MyCalc c = new MyCalc();
      Console.WriteLine(“1 + 2 = {0}”, c.Add(1, 2));
      Console.WriteLine(“1 – 2 = {0}”, c.Subtract(1, 2));
      // Can also cast into IBasicMath to invoke extension.
      Console.WriteLine(“30 – 9 = {0}”,
        ((IBasicMath)c).Subtract(30, 9));
      // This would NOT work!
      // IBasicMath itfBM = new IBasicMath();
      // itfBM.Subtract(10, 10);
      Console.ReadLine();
    }

November 23, 2008 - Posted by ebeworld | Uncategorized | | No Comments Yet

No comments yet.

Leave a comment