C# Extension Methods


This entry is part 1 of 2 in the series C# Extension Methods

What are extension methods? As the name implies, they are methods that extend or add to the functionality of a class. We can do this without changing the source code of the original class. Also, we don’t need to create a new type that inherits from that. How is this possible?

We have a post called C# Introduction.

Mosh Hamedani, in his Udemy.com course video, illustrates a use of extension methods that we show here. We want to write an extension method that allows us to take in a long string and spit out a shortened string, shortened down to the number of words we specify. For example, we may take in several sentences that represent the text in a blog post. We want to create a “one-liner” of just the first few words and we need a function to do that. Our project is called ExtensionMethods as you can see from the namespace.

Below is what our main program looks like.

using System;
namespace ExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            string post = "This is supposed to be a very long blog post blah blah...";
            var shortededPost = post.Shorten(5);
            Console.WriteLine(shortededPost);
        }
    }
}

The next code listing is of a class in our project called ExtensionMethods.

using System.Linq;
namespace System
{
    public static class StringExtensions
    {
        public static string Shorten(this String str, int numberOfWords)
        {
            if (numberOfWords < 0) throw new ArgumentOutOfRangeException("numberOfWords should be greater than zero");

            if (numberOfWords == 0) return "";
            string[] words = str.Split(' ');
            if (words.Length <= numberOfWords) return str;
            return string.Join(" ", words.Take(numberOfWords)) + "...";
        }
    }
}

Notice that the extension method is a static method. More importantly, notice the this keyword.

Let’s just experiment a little bit with the Main program.

using System;
namespace ExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            string post = "This is supposed to be a very long blog post blah blah...";
            var shortededPost = post.Shorten(5);
            var sp2 = shortededPost.ToUpper();
            var sp3 = sp2.PadRight(60);
            //shortededPost.PadRight(60);
            Console.WriteLine("[" + sp3 + "]");
        }
    }
}

Here is another example. It’s similar, but we notice that we can chain the method calls and they operate in order from left to right.

using System;
namespace ExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            string senten = "A very very long sentence...";
            Console.WriteLine("Number of characters: " + senten.Length);
            var shortededSentence = senten.Shorten(4);
            var s2 = shortededSentence.ToUpper();
            var s3 = s2.PadRight(60);
            Console.WriteLine("[" + s3 + "]");
            //
            string sent = "A very extremely long drawn-out sentence...";
            var s4 = sent.Shorten(4).ToUpper().PadRight(60);
            Console.WriteLine("[" + s4 + "]");
            var s5 = sent.PadRight(60).Shorten(4).ToUpper();
            Console.WriteLine("[" + s5 + "]");
            Console.WriteLine("chaining executes functions from left to right");
        }
    }
}

Below is the console output.

Number of characters: 28
[A VERY VERY LONG...                                         ]
[A VERY EXTREMELY LONG...                                    ]
[A VERY EXTREMELY LONG...]
chaining executes functions from left to right
Press any key to continue . . .
Series NavigationC# Extension Methods 2 >>