Extension methods with C# 2


gem I recently had the need of a method that could take the first letter of a word and change it to uppercase. While creating a method to do this wasn’t hard, I began to think that creating an extension method for string might be a better way to go.

So what is an extension method, a bit of Googleling and we find the MSDN documentation Extension Methods (C# Programming Guide) Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Well that’s a mouthful but what does it mean? Lets look at type string, you have probably used s.tolower() or s.trim() in the past, well tolower() and trim() are just extensions methods to the type string. Wouldnt it be nice if we could make something like s.UpperCaseFirstWord();

UpperCaseFirstWord method

In the following code I have created a method called UpperCaseFirstWord which takes a string parameter and returns the string first word uppercase. This solution is simple strait forward and it works, but its not very elegant is it?

using System;
class Program
{
    static void Main()
    {
	Console.WriteLine(UpperCaseFirstWord("jack and Jill went up the hill to fetch a pail of water."));
	Console.WriteLine(UpperCaseFirstWord("jack fell down and broke his crown,And Jill came tumbling after."));
    }
    static string UpperCaseFirstWord(string s)
    {
	// Check for empty string.
	if (string.IsNullOrEmpty(s))
	{
	    return string.Empty;
	}
	// Return char and concat substring.
	return char.ToUpper(s[0]) + s.Substring(1);
    }
}

UpperCaseFirstWord string extension

While the previous UpperCaseFirstWord example worked, it really wasn’t the elegant solution i was looking for. What if we could do something like this.

string text =  "jack and Jill went up the hill to fetch a pail of water.";
text = text.UpperCaseFirstWord();

Or really crazy like.

 string text = "jack and Jill went up the hill to fetch a pail of water.".UpperCaseFirstWord();

Well we can we just need to make an extension of the string type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomExtensions
{
    //Extension methods must be defined in a static class
    public static class StringExtension
    {       
        // This is the extension method.
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined.
        public static string UpperCaseFirstWord(this string s)
        {
            // Check for empty string.
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }

            // Return char and concat substring.
            return char.ToUpper(s[0]) + s.Substring(1);

        }
    }
}

[wp_ad_camp_3]
Now we can call it by using.

using CustomExtensions;

namespace Samples
{
    class Program
    {      
        static void Main(string[] args)
        {  
            string text = "jack and Jill went up the hill to fetch a pail of water.".UpperCaseFirstWord();
        }
    }
}

Conclusion

Extension Methods in C# can be extremely uses full when you want to extend the functionality of existing types. This was a very simple example, but I can think of some others.


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 thoughts on “Extension methods with C#