Please enable Javascript for better experience...
An introduction to Extension methods in C#
By Big | Jan 15, 2015 | In Articles | Update: Jul 17, 2015 | Total Views [ 1446 ]
Taged In
(2 Like)
Rate

In this article I will try to explain about extension methods in c# with an example.

Introduction

Extension methods are the special static methods which are defined on a type without creating a new derived type and can be called by that type. You would have used methods like Any(), Count(), Where(), Select() and many more while using linq queries in your applcation. These all are extension methods. You can create your own extension method on any type you want. We will see this with a simple example in later discussion. For more info please click on MSDN.

Using the code

Before going further let see how we can identify that a method is an extension method or not. Identifying extension method is very easy. You can find it with the types or with an arrow key pointing down. Below extension method is a custom method I defined on Integer type.

Let's try creating few extension methods. In this example I will try to create extension methods on integer and string type. Let's see it step by step.

Step 1: Create a static class

Add a static class and name it ExtensionClass.

    public static class ExtensionClass
    {
        //Add your extension methods
    }

Step 2: Define extension methods

Let's define an extension methods to square an integer.

To create an extension method make the method static and pass this keyword with the type you want like this.
public static int Square(this int i)

Below method will calculate square of given integer value. This extension method is created for int type and will return an integer as a return value.

        /// <summary>
        /// Method will square the value
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static int Square(this int i)
        {
            return i * i;
        }

Let's add another extension method to calculate factorial of integer. Method will calculate factorial of integer value.

        /// <summary>
        /// It will calculate factorial of integer value
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static int Factorial(this int i)
        {
            int factorial = 1;
            for (int j = i; j > 0; j--)
            {
                factorial *= j;
            }
            return factorial;
        }

Let's see one more example. In below example extension method is defined for integer type but will return string as return value.

        /// <summary>
        /// It will calculate value and return string value
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static string TestAge(this int i)
        {
            string mess = string.Empty;
            if (i >= 18)
                return "You are eligible";
            else
                return "Sorry you are not eligible";
        }

In above example extension method will take integer value and will return a string. Now let's try to add an extension method on string type.

        /// <summary>
        /// Extension method for string variable
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string Welcome(this string name)
        {
            return "Hey " + name + ". Welcome to Dot Net Concept.";
        }

Below is my final extension class which has all the methods I defined so far. My Extension class look like this. You can create extension methods for any type like integer, string or even a class created by you.

    public static class ExtensionClass
    {
        /// <summary>
        /// Method will square the value
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static int Square(this int i)
        {
            return i * i;
        }

        /// <summary>
        /// It will calculate factorial of integer value
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static int Factorial(this int i)
        {
            int factorial = 1;
            for (int j = i; j > 0; j--)
            {
                factorial *= j;
            }
            return factorial;
        }

        /// <summary>
        /// It will calculate value and return string value
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static string TestAge(this int i)
        {
            string mess = string.Empty;
            if (i >= 18)
                return "You are eligible";
            else
                return "Sorry you are not eligible";
        }

        /// <summary>
        /// Extension method for string variable
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string Welcome(this string name)
        {
            return "Hey " + name + ". Welcome to Dot Net Concept.";
        }
    }

Step 3: Implement in code

Now let's see how can we call these extension methods in program. Calling extension method is very easy. Just put dot(.) after variable name and it will pop up.

    class Program
    {
        static void Main(string[] args)
        {
            #region  Extension Method

            int i = 5;
            string name = "John";

            // Output: Square of 5 is 25
            Console.WriteLine("Square of {0} is {1}", i, i.Square());

            // Output: Factorial of 5 is 120
            Console.WriteLine("Factorial of {0} is {1}", i, i.Factorial());

            // Output: Your eligibility test:Sorry you are not eligible
            Console.WriteLine("Your eligibility test:" + i.TestAge());

            // Output: Hey John.  Welcome to Dot Net Concept.
            Console.WriteLine(name.Welcome());

            Console.ReadKey();
            #endregion
        }
    }

I think it is much clear now. You can add extension methods on any type you like. Try yourself and use in your code.

Share this

About the Author

Big
Rahul Jha (Big)
Founder, Developer dotnet-concept.com
Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment