Click here to Skip to main content
13,628,655 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

9.5K views
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)
{
  action(obj);
  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.

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

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.

Random

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);

License

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

Share

About the Author


You may also be interested in...

Pro

Comments and Discussions

 
QuestionIsNullOrEmpty has an inexcusably bad implementation Pin
Qwertie7-Apr-16 21:14
memberQwertie7-Apr-16 21:14 
Question"Random" will be slow Pin
Qwertie7-Apr-16 20:59
memberQwertie7-Apr-16 20:59 
PraiseExcellent explanation... Pin
stpl.ashish4-Apr-16 23:52
professionalstpl.ashish4-Apr-16 23:52 
QuestionUse Case?? Pin
Kirk Wood4-Apr-16 10:53
memberKirk Wood4-Apr-16 10:53 
AnswerRe: Use Case?? Pin
Qwertie7-Apr-16 21:20
memberQwertie7-Apr-16 21:20 
GeneralMy vote of 5 Pin
_Vitor Garcia_4-Apr-16 4:52
member_Vitor Garcia_4-Apr-16 4:52 
GeneralMy vote of 5 Pin
witnes3-Apr-16 23:14
memberwitnes3-Apr-16 23:14 
QuestionEnumerable IsNullOrEmpty Pin
Jaxag31-Mar-16 23:21
memberJaxag31-Mar-16 23:21 
AnswerRe: Enumerable IsNullOrEmpty Pin
Member 124303481-Apr-16 0:56
memberMember 124303481-Apr-16 0: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
Web01-2016 | 2.8.180712.1 | Last Updated 1 Apr 2016
Article Copyright 2016 by Duke Of Haren
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid