Click here to Skip to main content
13,768,132 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


15 bookmarked
Posted 31 Mar 2016
Licenced CPOL

Cool .NET Extension Methods

, 31 Mar 2016
Rate this:
Please Sign up or sign in to vote.
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:

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

You can execute the method like this:

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

public static T Set<T>(this T obj, Action<T> action)
  return obj;

An Example

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:

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.


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

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

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.


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

The Method Itself

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

An Example

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

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

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

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

An Example

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

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

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

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

An Example

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


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


About the Author

You may also be interested in...

Comments and Discussions

QuestionIsNullOrEmpty has an inexcusably bad implementation Pin
Qwertie7-Apr-16 22:14
memberQwertie7-Apr-16 22:14 
Question"Random" will be slow Pin
Qwertie7-Apr-16 21:59
memberQwertie7-Apr-16 21:59 
PraiseExcellent explanation... Pin
connect ashish yadav5-Apr-16 0:52
professionalconnect ashish yadav5-Apr-16 0:52 
QuestionUse Case?? Pin
Kirk Wood4-Apr-16 11:53
memberKirk Wood4-Apr-16 11:53 
AnswerRe: Use Case?? Pin
Qwertie7-Apr-16 22:20
memberQwertie7-Apr-16 22:20 
GeneralMy vote of 5 Pin
_Vitor Garcia_4-Apr-16 5:52
member_Vitor Garcia_4-Apr-16 5:52 
GeneralMy vote of 5 Pin
witnes4-Apr-16 0:14
memberwitnes4-Apr-16 0:14 
QuestionEnumerable IsNullOrEmpty Pin
Jaxag1-Apr-16 0:21
memberJaxag1-Apr-16 0:21 
AnswerRe: Enumerable IsNullOrEmpty Pin
Member 124303481-Apr-16 1:56
memberMember 124303481-Apr-16 1:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05-2016 | 2.8.181116.1 | Last Updated 1 Apr 2016
Article Copyright 2016 by Retired Author
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid