Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • .Net extension method

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 158
    Comment on it

    Extension method in .net is very important feature and good practice for reusable code. Extension method is a static method of a static class that can be invoked using the instance method syntax. Extension methods are used to add new behaviors to an existing type without altering. In extension method "this" keyword is used with the first parameter and the type of the first parameter will be the type that is extended by extension method.

    Here is example very simple example of extension method :

    //defining extension method
    public static class MyExtensions
    {
     public static int WordCount(this String str)
     {
     return str.Split(new char[] { ' ', '.', ',' }).Length;
     }
    } 
     
    class Program
    {
     public static void Main()
     {
     string s = "Dot Net Tricks Extension Method Example";
     
     //calling extension method
     int i = s.WordCount();
     
     Console.WriteLine(i);
     }
    }

    So lots of this we do again and again with string list and lots of other object we can create our extension method to reuse that code.

    --
    Happy Coding :)

 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: