Click here to Skip to main content
12,400,183 members (59,015 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

108.5K views
574 downloads
31 bookmarked
Posted

Extension Method In C#

, 10 Jan 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
A brief discussion about extension methods in C#

Introduction

Extension methods are a new feature in C# 3.0. An extension method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types. We can say that it extends the functionality of an existing type in .NET. An extension method is a static method to the existing static class. We call an extension method in the same general way; there is no difference in calling.

Feature and Property of Extension Methods 

The following list contains basic features and properties of extension methods:

  1. It is a static method.
  2. It must be located in a static class.
  3. It uses the "this" keyword as the first parameter with a type in .NET and this method will be called by a given type instance on the client side.
  4. It also shown by VS intellisense. When we press the dot (.) after a type instance, then it comes in VS intellisense.
  5. An extension method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement.
  6. You can give any name for the class that has an extension method but the class should be static.
  7. If you want to add new methods to a type and you don't have the source code for it, then the solution is to use and implement extension methods of that type.
  8. If you create extension methods that have the same signature methods as the type you are extending, then the extension methods will never be called.

Using the Code

We create an extension method for a string type so string will be specified as a parameter for this extension method and that method will be called by a string instance using the dot operator.

Extension Method

In the above method WordCount(), we are passing a string type with this so it will be called by the string type variable, in other words a string instance.

Now we create a static class and two static methods, one for the total word count in a string and another for the total number of characters in a string without a space.

using System;
namespace ExtensionMethodsExample
{
   public static class Extension
    {
       public static int WordCount(this string str)
       {
           string[] userString = str.Split(new char[] { ' ', '.', '?' },
                                       StringSplitOptions.RemoveEmptyEntries);
           int wordCount = userString.Length;
           return wordCount;
       } 
       public static int TotalCharWithoutSpace(this string str)
       {
           int totalCharWithoutSpace = 0;
           string[] userString = str.Split(' ');
           foreach (string stringValue in userString)
           {
               totalCharWithoutSpace += stringValue.Length;
           }
           return totalCharWithoutSpace;
       }
    }
} 

Now we create an executable program that has a string as an input and uses an extension method to count the total words in that string and the total number of characters in that string then show the result in a console screen.

using System;
namespace ExtensionMethodsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string userSentance = string.Empty;
            int totalWords = 0;
            int totalCharWithoutSpace = 0;
            Console.WriteLine("Enter the your sentance");
            userSentance = Console.ReadLine();
            //calling Extension Method WordCount
            totalWords = userSentance.WordCount();
            Console.WriteLine("Total number of words is :"+ totalWords);
            //calling Extension Method to count character
            totalCharWithoutSpace = userSentance.TotalCharWithoutSpace();
            Console.WriteLine("Total number of character is :"+totalCharWithoutSpace);
            Console.ReadKey();
        }
    }
} 

Extension Method

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sandeep Singh Shekhawat
Software Developer
India India
Sandeep Singh Shekhawat is a Software Developer. He is awarded for C# Corner MVP(2013,2014 and 2015) and CodeProject MVP (2015). His three articles at CodeProject are prize wining in article competition. His more than 10 articles has been selected Article of the Day at Microsoft ASP.NET (http://www.asp.net/) community.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 4 Pin
Umesh AP19-Jul-16 0:08
memberUmesh AP19-Jul-16 0:08 
Questionwow why don't you just copy and paste next time rofk what dumd son ahole Pin
Member 1213242321-Nov-15 12:02
memberMember 1213242321-Nov-15 12:02 
GeneralMy vote of 4 Pin
Member 113003726-May-15 23:46
memberMember 113003726-May-15 23:46 
QuestionNice article. (Pretty much same from MSDN) Pin
SharmaMayank10-Feb-15 18:13
memberSharmaMayank10-Feb-15 18:13 
Questionawasome Tips Pin
Yogesh Kumar Tyagi1-Dec-14 18:20
professionalYogesh Kumar Tyagi1-Dec-14 18:20 
GeneralPretty nice Pin
柏瑛 胡20-Nov-14 16:30
member柏瑛 胡20-Nov-14 16:30 
GeneralRe: Pretty nice Pin
Sandeep Singh Shekhawat20-Nov-14 17:25
professionalSandeep Singh Shekhawat20-Nov-14 17:25 
GeneralVery Good article Pin
Deepan Maheshwaran12-Nov-14 22:55
memberDeepan Maheshwaran12-Nov-14 22:55 
AnswerExtension method tutorial Pin
negatestac5-Nov-14 1:40
membernegatestac5-Nov-14 1:40 
QuestionGood tip Pin
CJV_Xtream13-Jan-14 7:31
memberCJV_Xtream13-Jan-14 7:31 
AnswerRe: Good tip Pin
Sandeep Singh Shekhawat13-Jan-14 17:47
professionalSandeep Singh Shekhawat13-Jan-14 17:47 
GeneralMy vote of 1 Pin
r.wcs13-Jan-14 5:07
memberr.wcs13-Jan-14 5:07 
GeneralRe: My vote of 1 Pin
Sandeep Singh Shekhawat13-Jan-14 5:12
professionalSandeep Singh Shekhawat13-Jan-14 5:12 
QuestionThanks Pin
rtz8712-Jan-14 7:01
memberrtz8712-Jan-14 7:01 
AnswerRe: Thanks Pin
Sandeep Singh Shekhawat12-Jan-14 17:14
professionalSandeep Singh Shekhawat12-Jan-14 17:14 
Question[My vote of 1] Nonsense Pin
FatCatProgrammer11-Jan-14 9:33
memberFatCatProgrammer11-Jan-14 9:33 
AnswerRe: [My vote of 1] Nonsense Pin
Sandeep Singh Shekhawat12-Jan-14 20:49
professionalSandeep Singh Shekhawat12-Jan-14 20:49 
GeneralMy vote of 5 Pin
M Rayhan10-Jan-14 19:51
memberM Rayhan10-Jan-14 19:51 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat10-Jan-14 20:03
professionalSandeep Singh Shekhawat10-Jan-14 20:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 10 Jan 2014
Article Copyright 2014 by Sandeep Singh Shekhawat
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid