Extension Methods in C#

Extension methods are used to add additional functionality to the class by adding more methods to it, without changing the original definition of the class. Extension methods are always static methods and belong to a static class. The first parameter of an extension method is the class which is being extended and this modifier is used with the parameter name. Have a look at the following example to understand this concept.

´╗┐using System;

namespace CSharpTutorials {
    public static class IntModifier {
        public static int Power(this int i, int j) {
            int result = i;
            for (int k = 1; k <= j; k++) result = result * i;            
            return result;        
    class Tutorial {
        static void Main (string[] args) {

Download the code

In the above code a static class named IntModifier has been declared which contains a static method called TakeRoot. This static method has “this” prefixed with the first parameter which is of integer type. This means that this extension method shall extend the integer class. The next parameter is also an integer which denotes the power to which we want to raise our integer variable.

Inside the Main method TakeRoot method is being called on integer value of 10 and the power to which we take exponent of 10 is passed inside the parameter i.e. 3. The output of this method will be 1000 which shall be displayed on the screen.

Note, in the above example we did not change the actual implementation of the integer class, but we added an additional method which can help us easily take the power of integer variable to any desired number.

<<< Exception Handling in C#Namespaces in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .