Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » String & StringBuilder » Extending The String Class

Extending The String Class

This article will show you a technique (new for C# 3.0) that allows you to extend the string class inside the .NET framwork to include your own string methods.

Author Rank:
Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads : 105
Total page views :  9332
Rating :
 5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ExtendingStrings.zip
 
ArticleAd
Become a Sponsor



 

 

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.

 


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ExtendingStrings.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Thanks!Guido9/24/2008
This was exactly what I was looking for. Thank You!
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved