Click here to Skip to main content
15,125,968 members
Articles / All Topics
Technical Blog
Posted 5 Jun 2017

Tagged as

Stats

3.8K views
2 bookmarked

Extend Classes using Extension Methods

Rate me:
Please Sign up or sign in to vote.
4.80/5 (2 votes)
5 Jun 2017CPOL2 min read
How to extend classes using extension methods

Extension Methods

Extension methods allow you to add your own custom method to an existing type. While this seems like a cool feature, there are a few reasons to use extension methods sparingly.

  • Adding too many extension methods to an existing type clutters the API.
  • If you name your extension method the same as a built-in method, yours will never be called.
  • If you name your extension method the same as another extension method, your method shadows the other extension method.

Because of the above points, you might consider just inheriting from the existing type and adding your own additional methods to this new class. But, with these disclaimers in place, let’s learn how you create extension methods because there are cases where using them is perfectly acceptable.

To create extension methods, you define a static class with any name you like. Listing 1 shows a class named StringExtensions. This listing shows a couple of the available methods such as ReverseString and ToBoolean. All extension methods must also use the static keyword. The first parameter passed to an extension method is the same as the type you are extending and must be prefixed with the keyword “this”. Creating classes and methods using these rules informs the compiler to add these methods to the type specified in the first parameter.

C#
public static class StringExtensions
{
  public static string Reverse(this string value)
  {
    char[] charArray = null;
    string ret = string.Empty;
    if (value != null)
    {
      charArray = value.ToCharArray();
      Array.Reverse(charArray);
      ret = new string(charArray);
    }
    return ret;
  }
  public static bool ToBoolean(this string value)
  {
    bool ret = false;
      
    switch (value.ToLower())
    {
      case "true":
      case "t":
      case "yes":
      case "y":
      case "1":
      case "-1":
        ret = true;
        break;
      case "false":
      case "f":
      case "no":
      case "n":
      case "0":
        ret = false;
        break;
      default:
        ret = false;
        break;
    }
    return ret;
  }
}
Listing 1: The StringExtensions class extends the string class with additional methods.

To use the methods shown in Listing 1, create an instance of type you are extending. After your new variable type, a dot (.) and your extension methods show up in the IntelliSense as shown in Figure 1.

Figure 1: Using extension methods is the same as any other method on a type.

Summary

Extension methods are cool in that you can add methods to classes that you do not have the source to. However, be careful not to overuse them. You don't want the API to grow too large for a single class. You might consider using inheritance instead.

License

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

Share

About the Author

Paul D. Sheriff
Employed (other) PDS Consulting
United States United States
Paul has been in the IT industry over 34 years. In that time he has successfully assisted hundreds of companies architect software applications to solve their toughest business problems. Paul has been a teacher and mentor through various mediums such as video courses, blogs, articles and speaking engagements at user groups and conferences around the world. Paul has 25 courses in the www.pluralsight.com library (https://www.pluralsight.com/author/paul-sheriff) on topics ranging from JavaScript, Angular, MVC, WPF, XML, jQuery and Bootstrap. Contact Paul at psheriff@pdsa.com.

Comments and Discussions

 
Generalstring.Reverse() Pin
Michael S. Post6-Jun-17 9:21
MemberMichael S. Post6-Jun-17 9:21 
QuestionCode in Listing1 formatting Pin
Niels Peter Gibe6-Jun-17 2:13
MemberNiels Peter Gibe6-Jun-17 2:13 

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.