开发者

C# - Example of Extension Method

Please could someone provide me with 开发者_开发百科a simple extension method that for example squares a number.

I have drawn up so pseudo code:

class Program

int = x
---------------------

public static int square (this int x)

return x * square


public static class NumberExtensions
{
  public static int Square(this int n)
  {
    return n*n;
  }
}

Now you can say:

int number=5.Square();


Here is how you would write the method:

public static class ExtnMethods 
{
    public static int Square(this int x)
    {
        return x * x;
    }
}

Some important things to note about the above code:

  • The class must be static and non-abstract
  • The parameter this int x specifies that the method acts on an int

You would use it like so:

Console.WriteLine(5.Square());
// prints 25


public static class SomeClass { 
   public static int Square(this int x) {
      return x * x;
   }
}


The extension method:

static class MathExtensions {

  public static Int32 Square(this Int32 x) {
    return x*x;
  }

}

How to use it:

var x = 5;
var xSquared = x.Square();


In this example I tried to show you how use multiple Extension method in a single expression.

class Program
{
    static void Main(string[] args)
    {
        int x = 13;
        var ans = x.Cube().Half().Square();
        Console.WriteLine(ans);
    }
}

static class IntExtensions
{
    public static int Half(this int source)
    {
        return source / 2;
    }
    public static int Cube(this int source)
    {
        return (int)Math.Pow(source, 3);
    }
    public static int Square(this int source)
    {
        return (int)Math.Pow(source, 2);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜