How do I extend a class with c# extension methods?

David Glenn picture David Glenn · Jul 27, 2009 · Viewed 146.5k times · Source

Can extension methods be applied to the class?

For example, extend DateTime to include a Tomorrow() method that could be invoked like:

DateTime.Tomorrow();

I know I can use

static DateTime Tomorrow(this Datetime value) { //... }

Or

public static MyClass {
  public static Tomorrow() { //... }
}

for a similar result, but how can I extend DateTime so that I could invoke DateTime.Tomorrow?

Answer

Kumu picture Kumu · Dec 31, 2009

Use an extension method.

Ex:

namespace ExtensionMethods
{
    public static class MyExtensionMethods
    {
        public static DateTime Tomorrow(this DateTime date)
        {
            return date.AddDays(1);
        }    
    }
}

Usage:

DateTime.Now.Tomorrow();

or

AnyObjectOfTypeDateTime.Tomorrow();