Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Cool .NET Extension Methods

4.78/5 (14 votes)
31 Mar 2016CPOL3 min read 14.3K  
Cool .NET extension methods

In this article, I’ll let you show some cool extension methods which you can use right away in your .NET project; they don’t need any external libraries (apart from .NET) to be executed.

Extension Methods?

I'll explain what extension methods are if you didn’t know this already. They are one of the things I really love about the .NET framework. An extension method is essentially a static method in a static class that accepts parameters just like any other method. The big difference is the "this" modifier for the first parameter in the method. Let’s take a look:

C#
public static string Blah(this string input)
{
    return input.Replace("blah", "foo");
}

You can execute the method like this:

C#
string text = "blahblah";
text = text.Blah();
Console.WriteLine(text); //foofoo

As you can see, you can now directly invoke the Blah() method on the string, like it’s an instance method (but it isn’t). Visual Studio knows about your extension and gives you intellisense when you want to invoke a method on your variable.

Besides this, extension methods are just static methods and some people may call it a code smell. This article is, however, about extension methods which make your development life a little bit easier.

'Set' Function

This is an extension method on the object class in .NET, which means every instance of every object has this extension method available. This extension method accepts an instance of a class and passes it to a callback method, where you can change the instance. The instance is then returned.

The Method Itself

C#
public static T Set<T>(this T obj, Action<T> action)
{
  action(obj);
  return obj;
}

An Example

C#
Person person = new Person().Set(p =>
{
  p.FirstName = "John";
  p.LastName = "Doe";
  p.Address = "Groningen, Netherlands";
  p.DateOfBirth = new DateTime(1993, 8, 29);
});

This is the more traditional way to write such an expression:

C#
Person person = new Person()
{
  FirstName = "John",
  LastName = "Doe",
  Address = "Groningen, Netherlands",
  DateOfBirth = new DateTime(1993, 8, 29)
};

I use the Set method a lot in unit tests, because it allows me to quickly set up a big mock data set. It also allows me to directly execute method calls when assigning variables.

WhereIf

This is a LINQ extension method. In essence, this is a method which accepts a boolean and an expression. If the boolean is true, the expression is executed. If the boolean is false, the expression is not executed, so the WhereIf statement is basically ignored.

The Method Itself

C#
public static IEnumerable<TSource> WhereIf<TSource>
(this IEnumerable<TSource> source, bool shouldExecute, Func<TSource, bool> predicate)
{
  if (shouldExecute)
  {
    return source.Where(predicate);
  }
  return source;
}

An Example

C#
var items = new List<string>() { "aa", "ab", "ba", "bb" };
var subItems = items.WhereIf(false, i => i.StartsWith("a")).ToList();

Because the boolean is false, the expression is not executed so the original list will be returned.

Random

This is a method which returns a random element from any IEnumerable.

The Method Itself

C#
public static T Random<T>(this IEnumerable<T> enumerable)
{
  return enumerable.OrderBy(e => Guid.NewGuid()).FirstOrDefault();
}

An Example

C#
var items = new List<string>() { "aa", "ab", "ba", "bb" };
var randomItem = items.Random();

It is not "really" random, as GUID is used for picking the item, but it's random enough for practical use.

Random Selection

This extension method accepts any enumerable and returns a random selection of count items.

The Method Itself

C#
public static IEnumerable<T> RandomSelection<T>(this IEnumerable<T> enumerable, int count)
{
  count = enumerable.Count() < count ? enumerable.Count() : count;
  return enumerable.OrderBy(e => Guid.NewGuid()).Take(count);
}

An Example

C#
var numbers = Enumerable.Range(0, 100);
var randomSelection = numbers.RandomSelection(10).ToList();

An array with numbers from 0 to 100 is defined. The second line gives us a random selection of those numbers.

Enumerable IsNullOrEmpty

This is a simple extension that takes any enumerable and checks if it is null or if the length is 0.

The Method Itself

C#
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
    return enumerable == null || enumerable.Count() == 0;
}

An Example

C#
string[] stringArray = new string[0];
bool empty = stringArray.IsNullOrEmpty(); //true

Parse Enum by String

This is a simple extension method which accepts an Enum type and a string. The method then tries to parse this string to an Enum value.

The Method Itself

C#
public static T ParseEnum<T>(this string input) where T : struct, IConvertible
{
  if (!typeof(T).IsEnum)
  {
    throw new ArgumentException("{0} is not an Enum", typeof(T).Name);
  }
  T result = default(T);
  Enum.TryParse(input, out result);
  return result;
}

An Example

C#
string value = "Monday";
DayOfWeek dayOfWeek = value.ParseEnum<DayOfWeek>();

AppendFormatLine for StringBuilder

I love the StringBuilder. It is one of the most efficient ways to generate a string in the .NET framework. I didn't like the fact that there was no direct method available to do a string format and a new line. This extension method does just that.

The Method Itself

C#
public static StringBuilder AppendFormatLine
(this StringBuilder stringBuilder, string format, params object[] args)
{
    return stringBuilder.AppendLine(string.Format(format, args));
}

An Example

C#
StringBuilder builder = new StringBuilder();
builder.AppendFormatLine("This is line {0}.", 1);
builder.AppendFormatLine("This is line {0}.", 2);

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)