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

console-application-in-csharp.png

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


extension-method-in-csharp.png


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

output-of-application.png

I hope this article is useful for you.