Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Extension methods in c#

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 220
    Comment on it

    Hello Friends, In this blog I will explain what is Extension method in c# ?

    Extension Methods:- Extension method helps you to add new methods to an existing types (like any Predefined dll or class etc.) without creating new derived types or modifying the original types.

    Example:- In development you are using many third party components. In below code I have used one third party dll for performing the mathematical operation like addition, subtraction and multiplication etc.

     class MathematicalOperation
    {
      static void Main (string [] args)
      {
         MathsOperation objectMathsOperation  =new MathsOperation()  // third party dll initialization 
         Console.WriteLine(objectMathsOperation.Addition(45,40));  //calling dll addition methods and taking input
         Console.ReadLine(); //Read the input
      }
    } 
    

    In above example we are using third party Addition methods using two input parameter. But Now we need to perform five numbers addition, subtraction etc. So we can achieve this functionality in many ways like create your own custom function, or may be added a new methods on third party dll. But in most of cases we have not third dll source code. So we can create extension methods for achieving this.

    Extension method creation :-

    public static class AddExtensionMethods
    {
      public static int FiveElementsAdditions(this MathsOperation  obj,int i, intj,int k, int l, int m)
      {
    // this MathsOperation  obj  is used to define the extension methods.
        return int i+ int j +int k +int l +int m ;
       }
    }
    

    After creating above function we can easily use FiveElementsAdditions methods.

     class MathematicalOperation
    {
      static void Main (string [] args)
      {
         MathsOperation objectMathsOperation  =new MathsOperation()  // third party dll initialization 
         Console.WriteLine(objectMathsOperation.FiveElementsAdditions (45,40,10,12,8));  //calling extension methods and taking input
         Console.ReadLine(); //Read the input
      }
    } 
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: