Extending The String Class


 

 

Figure 1 - Extending the String Class

Introduction

A while ago I wrote an article on a strategy for extending the string class in the .NET Framework.  The problem with extending many .NET 2.0 classes was that they were sealed, so you could not inherit from them, making extending them painful.  Well it looks like Microsoft has waved their magic wand once again and solved the problem in .NET 3.5.  You can now extend classes in the .NET framework.  In fact you can extend any class in which you can access!  This is exciting news for programmers who had a long wish list of functions they wanted for a class in .NET.  It's actually very easy to extend a class in C# and in this article we will show you how.

Extension Methods

Extension methods are static methods contained in a static class that allow you to extend another classes method.  Although not a very object-oriented concept (it also reminds me a little bit of the "friend" modifier in C#), it does give us the means to extend the .NET framework classes when inheritance is not available.  Below is a sample extension class:

Listing 1 - Extension Method Sample
namespace MyExtensions
{
 
public static class DebugExtensions
   {
     
public static void Print(this object anObject, string message)
      {
           
Console.WriteLine(String.Format("{0} {1}", message, anObject));
      }
  }
}

The this keyword in front of the object type in the Print method marks the Print method as an extension method.  Because the Print method defines a parameter this object, the Print method can extend every class that inherits from the object type!  To some this may seem a bit dangerous, but it does provide a way to print debug info on every possible class that include the using MyExtensions in the class file.  For Example you can use Print method extension on an integer as well as a string as shown in listing 2:

Listing 2 - Implementing the Extension Method

using MyExtensions;

int x = 54;
x.Print(
"The number is");

string msg = "Go to C# Corner";
msg.Print("The Message is");

Extending the string class

Although the object extension is perhaps a bit type unsafe, you can extend a specific class called myclass just by using  this myclass.   Below we extended the string class with this string.  This way only the string class can use the extended methods.  Any other class trying to use the string extension methods will throw a compilation error.  We've provided five string extensions in our example.  With a little thinking, I'm sure one can think of many more possibilities.  The methods are defined in the table below (you may recognize some of them from the early VB days).

Table 1 - String Method Extensions

String Extension Method Description
string Left (int count) Gets the first count characters of the string
string Right(int count) Gets the last count characters of a string
string Mid(int index, int count) Gets count characters starting at index
bool IsInteger Determines if the string is an integer
ToInteger Converts the string to an integer

Note that most of these methods are trivial and can easily be realized via other classes in the .net framework.  They just provide a good example of how you can extend the framework to suit your needs. Listing 2 shows the implementation of the string extension methods listed in table 1:

Listing 3 - Some String Extensions for the System.String class

 

using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Text.RegularExpressions;

namespace Extensions
{

public static class StringExtensions
{
  
public static string Left(this string s, int count)
   {
   
return s.Substring(0, count);
   }

  public static string Right(this string s, int count)
   {
     
return s.Substring(s.Length - count, count);
   }

   public static string Mid(this string s, int index, int count)
    {
     
return s.Substring(index, count);
    }

   public static int ToInteger(this string s)
   {
    
int integerValue = 0;
    
int.TryParse(s, out integerValue);
    
return integerValue;
   }

   public static bool IsInteger(this string s)
    {
     
Regex regularExpression = new Regex("^-[0-9]+$|^[0-9]+$");
     
return regularExpression.Match(s).Success;
    }

}

}

Implementing the string extension methods is done the same way you would implement any other string method.  You just need to include using Extensions at the top of your class and call your new string methods:

Listing 4 - Implementing String Extension Methods

using Extensions;
namespace
ExtendingStrings
{
 
class Program
   {
    
static void Main(string[] args)
      {
        
string test = "HelloWorld";
        
Console.WriteLine(test.Left(5));
        
Console.WriteLine(test.Right(5));
        
Console.WriteLine("{0}!!", test.Mid(5,2));
        
if (test.IsInteger())
          {
                   
Console.WriteLine("value = {0}", test.ToInteger());
          }

    test = "42";

    if (test.IsInteger())
     {
          
Console.WriteLine("value = {0}", test.ToInteger());
     }

      Console.ReadLine();
  }

}

}

The results of the running the console program in listing 4 are shown in Figure 2 below.  The Left(5) pulls out the first 5 letters of "HelloWorld",  the Right(5) pulls out the last 5 characters of "HelloWorld", and the Mid(5,2) pulls out the middle 2 characters of "HelloWorld" starting at index 5.   The IsInteger method checks to see if test is an integer.  Since "HelloWorld" is not an integer, it doesn't print anything.  When test is converted to the string "42", it is detected as an integer and printed on the screen.

Figure 2 - Output from String Extension Sample Program

Conclusion

Coming from an O-O UML background, it might seem strange to be writing an article on method extensions which are very much a structured (functional) implementation.  However, with the .NET framework making it impossible to override certain classes with an inheritance model,  extension methods are a more acceptable solution over a composite model as talked about in my previous article.  I don't think extension methods are necessary in classes you create yourself since you have full control over the contents of the class's members.  Anyway, Microsoft once again has provided a good way to extend your abilities in the .NET framework, so take advantage of it using C# and .NET.

 

Up Next
    Ebook Download
    View all
    Learn
    View all