Introduction
Today, in this article let's play around with one of the interesting and most useful concept in C#.
Question: What are extension methods?
In simple terms "Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type."
Step 1: Create a new console application

Step 2: The complete code of Arithmetic.cs looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodsApp
{
public static class Arithmetic
{
public static double Add(this double a, double b)
{
return a + b;
}
public static double Sub(this double a, double b)
{
return a - b;
}
public static double Mul(this double a, double b)
{
return a * b;
}
public static double Div(this double a, double b)
{
return a / b;
}
}
}
Step 3: The extension methods showing in intellisense looks like this

Step 4: The complete code of Program.cs looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodsApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Addition Result is: " + Arithmetic.Add(2, 2));
Console.WriteLine("Substraction Result is: " + Arithmetic.Sub(2, 1));
Console.WriteLine("Multiplication Result is: " + Arithmetic.Mul(2, 5));
Console.WriteLine("Division Result is: " + Arithmetic.Div(2, 12));
Console.ReadKey(true);
}
}
}
Step 5: The output of the application looks like this

I hope this article is useful for you.


Deepali PatilPosted Oct 14, 2012, 11:16 PM EDT
Hi.Nice article. Can you please tell me the advantages of using extension methods and when should we use it? Thanks:)