Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Extension Methods in C#

0.00/5 (No votes)
21 Jul 2011 1  
Extension methods in C#

As the name implies, extension methods allow existing classes to be extended without using inheritance or changing class’s source code.

Some important points when using extension methods are as follows:

  • You cannot use extension methods to override existing methods
  • An extension method with the same name and signature as an instance method must not be called
  • The concept must not be applied to fields, properties or events
  • Do not overuse

As an example, we’ll create an extension method to the existing ‘String’ class. We’ll implement the functionality of converting a string to a proper case. (Any given string will be converted to lower case, having the first letter of each word in upper case. For example, ‘this is sample text’ will be converted to ‘This Is Sample Text’).

Add a class and add the following code:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExtensionMethods {
public static class SampleExtensionMethods {
public static string ToProper(this string zSource) {
StringBuilder sb = new StringBuilder();

string zTemp = zSource.ToLower();
List<string> data = zTemp.Split(new char[] { ' ' }).ToList<string>();
if (data.Count > 0) {
foreach (string element in data) {
if (element.Trim().Length > 0) {
sb.Append(element.Trim().Substring(0, 1).ToUpper() + element.Trim().Substring(1, 
    element.Trim().Length - 1) + " ");
}
}
}

return sb.ToString().Trim();
}
}
}

Please note that the class should be static and the method should be public (unless you are writing it within the same class which you intend to use it). And also in input the parameter I have mentioned 'this'. This will tell the compiler to add the following method to the 'String' class.

Before using, include the namespace. (I have used 'ExtensionMethods' as the namespace):

C#
using ExtensionMethods;

And you can use the method we created using this syntax:

C#
SomeStringVar.ToProper()

For example:

C#
using System;
using System.Text;
using ExtensionMethods;

namespace SampleConsoleApplicationA {
class SampleExtMethod {
static void Main(string[] args) {
string zSample = "this is sample text";
Console.WriteLine("Input : " + zSample);
Console.WriteLine("Output : " + zSample.ToProper());
Console.ReadLine();
}
}
}

And if you run the application, you can get the below output (I have used a console application to illustrate this):

Extension Method

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here