478
votes

Let's make a list of answers where you post your excellent and favorite extension methods.

The requirement is that the full code must be posted and a example and an explanation on how to use it.

Based on the high interest in this topic I have setup an Open Source Project called extensionoverflow on Codeplex.

Please mark your answers with an acceptance to put the code in the Codeplex project.

Please post the full sourcecode and not a link.

Codeplex News:

24.08.2010 The Codeplex page is now here: http://extensionoverflow.codeplex.com/

11.11.2008 XmlSerialize / XmlDeserialize is now Implemented and Unit Tested.

11.11.2008 There is still room for more developers. ;-) Join NOW!

11.11.2008 Third contributer joined ExtensionOverflow, welcome to BKristensen

11.11.2008 FormatWith is now Implemented and Unit Tested.

09.11.2008 Second contributer joined ExtensionOverflow. welcome to chakrit.

09.11.2008 We need more developers. ;-)

09.11.2008 ThrowIfArgumentIsNull in now Implemented and Unit Tested on Codeplex.

4
  • Now the first code is committed to the Codeplex site.
    – bovium
    Commented Nov 7, 2008 at 20:13
  • Erik unfortunately everything is started now on codeplex. Please join anyway.
    – bovium
    Commented Nov 11, 2008 at 22:43
  • 3
    Looks pretty good. I do have a comment about naming the static classes. Naming them <type>Extensions isn't very informative. For example StringExtensions holds both formatting and xml stuff. I think it's better to name the class with why you're extending that type. For example UnixDateTimeConversions. You can reasonably guess it holds methods for converting to and from Unix time. Just a thought!
    – ecoffey
    Commented Aug 26, 2010 at 15:56
  • Check this URL for more about C# Extension Methods planetofcoders.com/c-extension-methods Commented Mar 9, 2012 at 5:59

150 Answers 150

4
votes

Converts a List to a datatable

public static class DataTableConverter
{
    /// <summary>
    /// Convert a List{T} to a DataTable.
    /// </summary>
    public static DataTable ToDataTable<T>(this IList<T> items)
    {
        var tb = new DataTable(typeof(T).Name);

        PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo prop in props)
        {
            Type t = GetCoreType(prop.PropertyType);
            tb.Columns.Add(prop.Name, t);
        }

        foreach (T item in items)
        {
            var values = new object[props.Length];

            for (int i = 0; i < props.Length; i++)
            {
                values[i] = props[i].GetValue(item, null);
            }

            tb.Rows.Add(values);
        }

        return tb;
    }

    /// <summary>
    /// Determine of specified type is nullable
    /// </summary>
    public static bool IsNullable(Type t)
    {
        return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
    }

    /// <summary>
    /// Return underlying type if type is Nullable otherwise return the type
    /// </summary>
    public static Type GetCoreType(Type t)
    {
        if (t != null && IsNullable(t))
        {
            if (!t.IsValueType)
            {
                return t;
            }
            else
            {
                return Nullable.GetUnderlyingType(t);
            }
        }
        else
        {
            return t;
        }
    }
}

Usage:

    IList<MyClass> myClassList = new List<MyClass>();
    DataTable myClassDataTable = myClassList.ToDataTable();
1
4
votes

These extension methods invoke an event asynchronously. They were inspired by this StackOverflow answer.

/// <summary>
/// Invoke an event asynchronously. Each subscriber to the event will be invoked on a separate thread.
/// </summary>
/// <param name="someEvent">The event to be invoked asynchronously.</param>
/// <param name="sender">The sender of the event.</param>
/// <param name="args">The args of the event.</param>
/// <typeparam name="TEventArgs">The type of <see cref="EventArgs"/> to be used with the event.</typeparam>
public static void InvokeAsync<TEventArgs>(this EventHandler<TEventArgs> someEvent, object sender, TEventArgs args)
    where TEventArgs : EventArgs
{
    if (someEvent == null)
    {
        return;
    }

    var eventListeners = someEvent.GetInvocationList();

    AsyncCallback endAsyncCallback = delegate(IAsyncResult iar)
    {
        var ar = iar as AsyncResult;
        if (ar == null)
        {
            return;
        }

        var invokedMethod = ar.AsyncDelegate as EventHandler<TEventArgs>;
        if (invokedMethod != null)
        {
            invokedMethod.EndInvoke(iar);
        }
    };

    foreach (EventHandler<TEventArgs> methodToInvoke in eventListeners)
    {
        methodToInvoke.BeginInvoke(sender, args, endAsyncCallback, null);
    }
}

/// <summary>
/// Invoke an event asynchronously. Each subscriber to the event will be invoked on a separate thread.
/// </summary>
/// <param name="someEvent">The event to be invoked asynchronously.</param>
/// <param name="sender">The sender of the event.</param>
/// <param name="args">The args of the event.</param>
public static void InvokeAsync(this EventHandler someEvent, object sender, EventArgs args)
{
    if (someEvent == null)
    {
        return;
    }

    var eventListeners = someEvent.GetInvocationList();

    AsyncCallback endAsyncCallback = delegate(IAsyncResult iar)
    {
        var ar = iar as AsyncResult;
        if (ar == null)
        {
            return;
        }

        var invokedMethod = ar.AsyncDelegate as EventHandler;
        if (invokedMethod != null)
        {
            invokedMethod.EndInvoke(iar);
        }
    };

    foreach (EventHandler methodToInvoke in eventListeners)
    {
        methodToInvoke.BeginInvoke(sender, args, endAsyncCallback, null);
    }
}

To use:

public class Foo
{
    public event EventHandler<EventArgs> Bar;

    public void OnBar()
    {
        Bar.InvokeAsync(this, EventArgs.Empty);
    }
}

Notice the added benefit that you don't have to check for null on the event before invoking it. e.g.:

EventHandler<EventArgs> handler = Bar;
if (handler != null)
{
    // Invoke the event
}

To test:

void Main()
{
    EventHandler<EventArgs> handler1 =
    delegate(object sender, EventArgs args)
    {
        // Simulate performing work in handler1
        Thread.Sleep(100);
        Console.WriteLine("Handled 1");
    };

    EventHandler<EventArgs> handler2 =
    delegate(object sender, EventArgs args)
    {
        // Simulate performing work in handler2
        Thread.Sleep(50);
        Console.WriteLine("Handled 2");
    };

    EventHandler<EventArgs> handler3 =
    delegate(object sender, EventArgs args)
    {
        // Simulate performing work in handler3
        Thread.Sleep(25);
        Console.WriteLine("Handled 3");
    };

    var foo = new Foo();
    foo.Bar += handler1;
    foo.Bar += handler2;
    foo.Bar += handler3;
    foo.OnBar();

    Console.WriteLine("Start executing important stuff");

    // Simulate performing some important stuff here, where we don't want to
    // wait around for the event handlers to finish executing
    Thread.Sleep(1000);

    Console.WriteLine("Finished executing important stuff");
}

Invoking the event will (usually) yield this output:

Start executing important stuff
Handled 3
Handled 2
Handled 1
Finished executing important stuff

If the event were invoked synchronously, it would always yield this output - and delay execution of the "important" stuff:

Handled 1
Handled 2
Handled 3
Start executing important stuff
Finished executing important stuff

4
votes

I actually just blogged this today. It's a strongly typed reactive wrapper around a INotifyPropertyChanged property.

GetPropertyValues returns an IObservable<T> of the values as they change, starting with the current value. If ignore the current value, you can just call Skip(1) on the result.

Usage is like so:

IObservable<int> values = viewModel.GetPropertyValues(x => x.IntProperty);

Implementation:

public static class NotifyPropertyChangeReactiveExtensions
{
    // Returns the values of property (an Expression) as they change, 
    // starting with the current value
    public static IObservable<TValue> GetPropertyValues<TSource, TValue>(
        this TSource source, Expression<Func<TSource, TValue>> property)
        where TSource : INotifyPropertyChanged
    {
        MemberExpression memberExpression = property.Body as MemberExpression;

        if (memberExpression == null)
        {
            throw new ArgumentException(
                "property must directly access a property of the source");
        }

        string propertyName = memberExpression.Member.Name;

        Func<TSource, TValue> accessor = property.Compile();

        return source.GetPropertyChangedEvents()
            .Where(x => x.EventArgs.PropertyName == propertyName)
            .Select(x => accessor(source))
            .StartWith(accessor(source));
    }

    // This is a wrapper around FromEvent(PropertyChanged)
    public static IObservable<IEvent<PropertyChangedEventArgs>>
        GetPropertyChangedEvents(this INotifyPropertyChanged source)
    {
        return Observable.FromEvent<PropertyChangedEventHandler, 
            PropertyChangedEventArgs>(
            h => new PropertyChangedEventHandler(h),
            h => source.PropertyChanged += h,
            h => source.PropertyChanged -= h);
    }
}
4
votes

I created a nice Each extension that has the same behavior as jQuery's each function.

It allows something like below, where you can get the index of the current value and break out of the loop by returning false:

new[] { "first", "second", "third" }.Each((value, index) =>
{
    if (value.Contains("d"))
        return false;
    Console.Write(value);
    return true;
});

Here's the code

/// <summary>
/// Generic iterator function that is useful to replace a foreach loop with at your discretion.  A provided action is performed on each element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action">Function that takes in the current value in the sequence. 
/// <returns></returns>
public static IEnumerable<T> Each<T>(this IEnumerable<T> source, Action<T> action)
{
    return source.Each((value, index) =>
    {
        action(value);
        return true;
    });
}


/// <summary>
/// Generic iterator function that is useful to replace a foreach loop with at your discretion.  A provided action is performed on each element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action">Function that takes in the current value and its index in the sequence.  
/// <returns></returns>
public static IEnumerable<T> Each<T>(this IEnumerable<T> source, Action<T, int> action)
{
    return source.Each((value, index) =>
    {
        action(value, index);
        return true;
    });
}

/// <summary>
/// Generic iterator function that is useful to replace a foreach loop with at your discretion.  A provided action is performed on each element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action">Function that takes in the current value in the sequence.  Returns a value indicating whether the iteration should continue.  So return false if you don't want to iterate anymore.</param>
/// <returns></returns>
public static IEnumerable<T> Each<T>(this IEnumerable<T> source, Func<T, bool> action)
{
    return source.Each((value, index) =>
    {
        return action(value);
    });
}

/// <summary>
/// Generic iterator function that is useful to replace a foreach loop with at your discretion.  A provided action is performed on each element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action">Function that takes in the current value and its index in the sequence.  Returns a value indicating whether the iteration should continue.  So return false if you don't want to iterate anymore.</param>
/// <returns></returns>
public static IEnumerable<T> Each<T>(this IEnumerable<T> source, Func<T, int, bool> action)
{
    if (source == null)
        return source;

    int index = 0;
    foreach (var sourceItem in source)
    {
        if (!action(sourceItem, index))
            break;
        index++;
    }
    return source;
}
1
  • How is it different from TakeWhile? (except for the overloads with Action) Commented May 18, 2011 at 22:43
4
votes

String.As<T>, which can be used to convert a string value as some type (intended to be used primarily with primitives and types that support IConvertable. Works great with Nullable types and even Enums!

public static partial class StringExtensions
{
    /// <summary>
    /// Converts the string to the specified type, using the default value configured for the type.
    /// </summary>
    /// <typeparam name="T">Type the string will be converted to. The type must implement IConvertable.</typeparam>
    /// <param name="original">The original string.</param>
    /// <returns>The converted value.</returns>
    public static T As<T>(this String original)
    {
        return As(original, CultureInfo.CurrentCulture,
                  default(T));
    }

    /// <summary>
    /// Converts the string to the specified type, using the default value configured for the type.
    /// </summary>
    /// <typeparam name="T">Type the string will be converted to.</typeparam>
    /// <param name="original">The original string.</param>
    /// <param name="defaultValue">The default value to use in case the original string is null or empty, or can't be converted.</param>
    /// <returns>The converted value.</returns>
    public static T As<T>(this String original, T defaultValue)
    {
        return As(original, CultureInfo.CurrentCulture, defaultValue);
    }

    /// <summary>
    /// Converts the string to the specified type, using the default value configured for the type.
    /// </summary>
    /// <typeparam name="T">Type the string will be converted to.</typeparam>
    /// <param name="original">The original string.</param>
    /// <param name="provider">Format provider used during the type conversion.</param>
    /// <returns>The converted value.</returns>
    public static T As<T>(this String original, IFormatProvider provider)
    {
        return As(original, provider, default(T));
    }

    /// <summary>
    /// Converts the string to the specified type.
    /// </summary>
    /// <typeparam name="T">Type the string will be converted to.</typeparam>
    /// <param name="original">The original string.</param>
    /// <param name="provider">Format provider used during the type conversion.</param>
    /// <param name="defaultValue">The default value to use in case the original string is null or empty, or can't be converted.</param>
    /// <returns>The converted value.</returns>
    /// <remarks>
    /// If an error occurs while converting the specified value to the requested type, the exception is caught and the default is returned. It is strongly recommended you
    /// do NOT use this method if it is important that conversion failures are not swallowed up.
    ///
    /// This method is intended to be used to convert string values to primatives, not for parsing, converting, or deserializing complex types.
    /// </remarks>
    public static T As<T>(this String original, IFormatProvider provider,
                          T defaultValue)
    {
        T result;
        Type type = typeof (T);

        if (String.IsNullOrEmpty(original)) result = defaultValue;
        else
        {
            // need to get the underlying type if T is Nullable<>.

            if (type.IsNullableType())
            {
                type = Nullable.GetUnderlyingType(type);
            }

            try
            {
                // ChangeType doesn't work properly on Enums
                result = type.IsEnum
                             ? (T) Enum.Parse(type, original, true)
                             : (T) Convert.ChangeType(original, type, provider);
            }
            catch // HACK: what can we do to minimize or avoid raising exceptions as part of normal operation? custom string parsing (regex?) for well-known types? it would be best to know if you can convert to the desired type before you attempt to do so.
            {
                result = defaultValue;
            }
        }

        return result;
    }
}

This relies on another simple extension for Type:

/// <summary>
/// Extension methods for <see cref="Type"/>.
/// </summary>
public static class TypeExtensions
{
    /// <summary>
    /// Returns whether or not the specified type is <see cref="Nullable{T}"/>.
    /// </summary>
    /// <param name="type">A <see cref="Type"/>.</param>
    /// <returns>True if the specified type is <see cref="Nullable{T}"/>; otherwise, false.</returns>
    /// <remarks>Use <see cref="Nullable.GetUnderlyingType"/> to access the underlying type.</remarks>
    public static bool IsNullableType(this Type type)
    {
        if (type == null) throw new ArgumentNullException("type");

        return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof (Nullable<>));
    }
}

Usage:

var someInt = "1".As<int>();
var someIntDefault = "bad value".As(1); // "bad value" won't convert, so the default value 1 is returned.
var someEnum = "Sunday".As<DayOfWeek>();
someEnum = "0".As<DayOfWeek>(); // returns Sunday
var someNullableEnum = "".As<DayOfWeek?>(null); // returns a null value since "" can't be converted
4
votes

I find the following extension method quite useful:

public static T GetService<T>(this IServiceProvider provider)
{
    return (T)provider.GetService(typeof(T));
}

It makes it much easier to use the IServiceProvider interface. Compare:

IProvideValueTarget target = (IProvideValueTarget)serviceProvider(typeof(IProvideValueTarget));

and

var target = serviceProvider.GetService<IProvideValueTarget>();
3
votes

I use these in my web projects, mainly with MVC. I have a handful of these written for the ViewData and TempData

/// <summary>
/// Checks the Request.QueryString for the specified value and returns it, if none 
/// is found then the default value is returned instead
/// </summary>
public static T QueryValue<T>(this HtmlHelper helper, string param, T defaultValue) {
    object value = HttpContext.Current.Request.QueryString[param] as object;
    if (value == null) { return defaultValue; }
    try {
        return (T)Convert.ChangeType(value, typeof(T));
    } catch (Exception) {
        return defaultValue;
    }
}

That way I can write something like...

<% if (Html.QueryValue("login", false)) { %>
    <div>Welcome Back!</div>

<% } else { %>
    <%-- Render the control or something --%>

<% } %>
2
  • Anyone can use it - Help yourself
    – hugoware
    Commented Nov 8, 2008 at 22:38
  • Very nice, could be expanded to first check Query string, then check ViewData, then check SessionState, finally return default value.
    – John
    Commented Apr 22, 2010 at 13:50
3
votes

Wildcard string comparison:

public static bool MatchesWildcard(this string text, string pattern)
{
    int it = 0;
    while (text.CharAt(it) != 0 &&
           pattern.CharAt(it) != '*')
    {
        if (pattern.CharAt(it) != text.CharAt(it) && pattern.CharAt(it) != '?')
            return false;
        it++;
    }

    int cp = 0;
    int mp = 0;
    int ip = it;

    while (text.CharAt(it) != 0)
    {
        if (pattern.CharAt(ip) == '*')
        {
            if (pattern.CharAt(++ip) == 0)
                return true;
            mp = ip;
            cp = it + 1;
        }
        else if (pattern.CharAt(ip) == text.CharAt(it) || pattern.CharAt(ip) == '?')
        {
            ip++;
            it++;
        }
        else
        {
            ip = mp;
            it = cp++;
        }
    }

    while (pattern.CharAt(ip) == '*')
    {
        ip++;
    }
    return pattern.CharAt(ip) == 0;
}

public static char CharAt(this string s, int index)
{
    if (index < s.Length)
        return s[index];
    return '\0';
}

It's a direct translation of the C code from this article, hence the CharAt method that returns 0 for the end of the string

if (fileName.MatchesWildcard("*.cs"))
{
    Console.WriteLine("{0} is a C# source file", fileName);
}
2
  • nice. Just what I'm looking for :-) Commented Aug 20, 2010 at 8:25
  • @aboveyou00, for performance mostly. Also, there's no obvious equivalence between a regex and a wildcard pattern, and a wildcard is easier to use if you don't need the full power of a regex. Commented Mar 21, 2012 at 14:43
3
votes

Here is the only extension that I wrote that I use regularly. It makes sending email with System.Net.Mail a bit easier.

public static class MailExtension
{
    // GetEmailCreditial(out strServer) gets credentials from an XML file
    public static void Send(this MailMessage email)
    {
        string strServer = String.Empty;
        NetworkCredential credentials = GetEmailCreditial(out strServer);
        SmtpClient client = new SmtpClient(strServer) { Credentials = credentials };
        client.Send(email);
    }

    public static void Send(this IEnumerable<MailMessage> emails)
    {
        string strServer = String.Empty;
        NetworkCredential credentials = GetEmailCreditial(out strServer);
        SmtpClient client = new SmtpClient(strServer) { Credentials = credentials };
        foreach (MailMessage email in emails)
            client.Send(email);
    }
}

// Example of use: 
new MailMessage("[email protected]","[email protected]","This is an important Subject", "Body goes here").Send();
//Assume email1,email2,email3 are MailMessage objects
new List<MailMessage>(){email1, email2, email}.Send();
3
votes

Didn't check the whole thread, so it may already be here, but:

public static class FluentOrderingExtensions
    public class FluentOrderer<T> : IEnumerable<T>
    {
        internal List<Comparison<T>> Comparers = new List<Comparison<T>>();

        internal IEnumerable<T> Source;

        public FluentOrderer(IEnumerable<T> source)
        {
            Source = source;
        }

        #region Implementation of IEnumerable

        public IEnumerator<T> GetEnumerator()
        {
            var workingArray = Source.ToArray();
            Array.Sort(workingArray, IterativeComparison);

            foreach(var element in workingArray) yield return element;
        }

        private int IterativeComparison(T a, T b)
        {
            foreach (var comparer in Comparers)
            {
                var result = comparer(a,b);
                if(result != 0) return result;
            }
            return 0;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }

    public static FluentOrderer<T> OrderFluentlyBy<T,TResult>(this IEnumerable<T> source, Func<T,TResult> predicate) 
        where TResult : IComparable<TResult>
    {
        var result = new FluentOrderer<T>(source);
        result.Comparers.Add((a,b)=>predicate(a).CompareTo(predicate(b)));
        return result;
    }

    public static FluentOrderer<T> OrderFluentlyByDescending<T,TResult>(this IEnumerable<T> source, Func<T,TResult> predicate) 
        where TResult : IComparable<TResult>
    {
        var result = new FluentOrderer<T>(source);
        result.Comparers.Add((a,b)=>predicate(a).CompareTo(predicate(b)) * -1);
        return result;
    }

    public static FluentOrderer<T> ThenBy<T, TResult>(this FluentOrderer<T> source, Func<T, TResult> predicate)
        where TResult : IComparable<TResult>
    {
        source.Comparers.Add((a, b) => predicate(a).CompareTo(predicate(b)));
        return source;
    }

    public static FluentOrderer<T> ThenByDescending<T, TResult>(this FluentOrderer<T> source, Func<T, TResult> predicate)
        where TResult : IComparable<TResult>
    {
        source.Comparers.Add((a, b) => predicate(a).CompareTo(predicate(b)) * -1);
        return source;
    }
}

Usage:

var myFluentlyOrderedList = GetABunchOfComplexObjects()
    .OrderFluentlyBy(x=>x.PropertyA)
    .ThenByDescending(x=>x.PropertyB)
    .ThenBy(x=>x.SomeMethod())
    .ThenBy(x=>SomeOtherMethodAppliedTo(x))
    .ToList();

... assuming of course that all the predicates return types that are IComparable to themselves. It would work better with a stable sort like a MergeSort instead of .NET's built-in QuickSort, but it provides you with readable multi-field ordering ability similar to SQL (as close as a method chain can get, anyway). You can extend this to accomodate members that aren't IComparable, by defining overloads that take a comparison lambda instead of creating it based on a predicate.

EDIT: A little explanation, since the commenter got some upticks: this set of methods improves upon the basic OrderBy() functionality by allowing you to sort based on multiple fields in descending order of importance. A real-world example would be sorting a list of invoices by customer, then by invoice number (or invoice date). Other methods of getting the data in this order either wouldn't work (OrderBy() uses an unstable sort, so it cannot be chained) or would be inefficient and not look like it does what you're trying to do.

6
  • 2
    How is this an advantage over the default OrderBy and OrderByDescending?
    – Agent_9191
    Commented Oct 20, 2010 at 11:38
  • OrderBy() cannot be chained; each call to OrderBy() sorts by a single projection of the collected type. You could still make it work if the sorting algorithm used were stable like MergeSort, but the built-in sorting helper is an unstable QuickSort, so there's no guarantee of maintaining relative order when sorting by equal terms. Chaining OrderBy() would also run an O(nlogn) function once for each OrderBy(); this set of methods sorts once no matter how many terms you compare.
    – KeithS
    Commented Oct 20, 2010 at 14:34
  • This could be improved by avoiding the ToArray(). While OrderBy cannot be chained, you should be able to chain all of the Comparers into an IComparer<T> that you pass to a single OrderBy, right?
    – scobi
    Commented Oct 22, 2010 at 18:44
  • Well, sorting (ANY algorithm) requires knowledge of the entire Enumerable, because the very last element could be the one that comes first in the ordered collection. OrderBy(), behind the scenes, basically does what I'm doing here; slurp the source Enumerable into a finite collection, sort it, then yield through it.
    – KeithS
    Commented Oct 22, 2010 at 19:54
  • 1
    Point taken. :) Also: how does this set of classes differ from the Enumerable.ThenBy() and IOrderedEnumerable types in the .NET Framework?
    – scobi
    Commented Oct 22, 2010 at 20:00
3
votes

Two color extensions I use, mostly for control development:

public static class ColorExtensions
{
  // Gets a color that will be readable on top of a given background color
  public static Color GetForegroundColor(this Color input)
  {
    // Math taken from one of the replies to
    // http://stackoverflow.com/questions/2241447/make-foregroundcolor-black-or-white-depending-on-background
    if (Math.Sqrt(input.R * input.R * .241 + input.G * input.G * .691 + input.B * input.B * .068) > 128)
      return Color.Black;
    else
      return Color.White;
  }

  // Converts a given Color to gray
  public static Color ToGray(this Color input)
  {
    int g = (int)(input.R * .299) + (int)(input.G * .587) + (int)(input.B * .114);
    return Color.FromArgb(input.A, g, g, g);
  }
}

Usage:

Color foreColor = someBackColor.GetForegroundColor();
Color grayColor = someBackColor.ToGray();
3
votes

The Substring method on the string class has always felt inadequate to me. Usually when you do a substring, you know the character(s) from where you want to start, and the charachter(s) where you want to end. Thus, I've always felt that have to specify length as the second parameter is stupid. Therefore, I've written my own extension methods. One that takes a startIndex and an endIndex. And one, that takes a startText (string) and endText (string) so you can just specify the text from where to start the substring, and the text for where to end it.

NOTE: I couldn't name the method Substring as in .NET because my first overload takes the same parameter types as one of the .NET overloads. Therefore I named them Subsetstring. Feel free to add to the CodePlex...

public static class StringExtensions
{
    /// <summary>
    /// Returns a Subset string starting at the specified start index and ending and the specified end
    /// index.
    /// </summary>
    /// <param name="s">The string to retrieve the subset from.</param>
    /// <param name="startIndex">The specified start index for the subset.</param>
    /// <param name="endIndex">The specified end index for the subset.</param>
    /// <returns>A Subset string starting at the specified start index and ending and the specified end
    /// index.</returns>
    public static string Subsetstring(this string s, int startIndex, int endIndex)
    {
        if (startIndex > endIndex)
        {
            throw new InvalidOperationException("End Index must be after Start Index.");
        }

        if (startIndex < 0)
        {
            throw new InvalidOperationException("Start Index must be a positive number.");
        }

        if(endIndex <0)
        {
            throw new InvalidOperationException("End Index must be a positive number.");
        }

        return s.Substring(startIndex, (endIndex - startIndex));
    }

    /// <summary>
    /// Finds the specified Start Text and the End Text in this string instance, and returns a string
    /// containing all the text starting from startText, to the begining of endText. (endText is not
    /// included.)
    /// </summary>
    /// <param name="s">The string to retrieve the subset from.</param>
    /// <param name="startText">The Start Text to begin the Subset from.</param>
    /// <param name="endText">The End Text to where the Subset goes to.</param>
    /// <param name="ignoreCase">Whether or not to ignore case when comparing startText/endText to the string.</param>
    /// <returns>A string containing all the text starting from startText, to the begining of endText.</returns>
    public static string Subsetstring(this string s, string startText, string endText, bool ignoreCase)
    {
        if (string.IsNullOrEmpty(startText) || string.IsNullOrEmpty(endText))
        {
            throw new ArgumentException("Start Text and End Text cannot be empty.");
        }
        string temp = s;
        if (ignoreCase)
        {
            temp = s.ToUpperInvariant();
            startText = startText.ToUpperInvariant();
            endText = endText.ToUpperInvariant();
        }
        int start = temp.IndexOf(startText);
        int end = temp.IndexOf(endText, start);
        return Subsetstring(s, start, end);
    }
}

Usage:

string s = "This is a tester for my cool extension method!!";
       s = s.Subsetstring("tester", "cool",true);

Output: "tester for my "

3
votes

While working with MVC and having lots of if statements where i only care about either true or false, and printing null, or string.Empty in the other case, I came up with:

public static TResult WhenTrue<TResult>(this Boolean value, Func<TResult> expression)
{
    return value ? expression() : default(TResult);
}

public static TResult WhenTrue<TResult>(this Boolean value, TResult content)
{
    return value ? content : default(TResult);
}

public static TResult WhenFalse<TResult>(this Boolean value, Func<TResult> expression)
{
    return !value ? expression() : default(TResult);
}

public static TResult WhenFalse<TResult>(this Boolean value, TResult content)
{
    return !value ? content : default(TResult);
}

It allows me to change <%= (someBool) ? "print y" : string.Empty %> into <%= someBool.WhenTrue("print y") %> .

I only use it in my Views where I mix code and HTML, in code files writing the "longer" version is more clear IMHO.

3
votes

Would be great to have Unix TimeStamp and ISO 8601 formatted date and times. heavily used in websites and rest services.

I use it in my Facebook Library. You can find the source http://github.com/prabirshrestha/FacebookSharp/blob/master/src/FacebookSharp.Core/FacebookUtils/DateUtils.cs

private static readonly DateTime EPOCH = DateTime.SpecifyKind(new DateTime(1970, 1, 1, 0, 0, 0, 0),DateTimeKind.Utc);

public static DateTime FromUnixTimestamp(long timestamp)
{
    return EPOCH.AddSeconds(timestamp);
}

public static long ToUnixTimestamp(DateTime date)
{
    TimeSpan diff = date.ToUniversalTime() - EPOCH;
    return (long)diff.TotalSeconds;
}

public static DateTime FromIso8601FormattedDateTime(string iso8601DateTime){
    return DateTime.ParseExact(iso8601DateTime, "o", System.Globalization.CultureInfo.InvariantCulture);
}

public static string ToIso8601FormattedDateTime(DateTime dateTime)
{
    return dateTime.ToString("o");
}

Feel free to use in the codeplex project.

2
  • I've written basically identical code myself on more than one occasion.
    – Greg D
    Commented Sep 11, 2010 at 13:42
  • Interesting. But not exactly extension methods.
    – fre0n
    Commented Sep 13, 2010 at 20:13
2
votes

An easier way to load default settings from a collection (in real life I use it to populate the settings from any source, including the command line, ClickOnce URL parameters etc.):

public static void LoadFrom(this ApplicationSettingsBase settings, NameValueCollection configuration)
{
    if (configuration != null)
        foreach (string key in configuration.AllKeys)
            if (!String.IsNullOrEmpty(key))
                try
                {
                    settings[key] = configuration.Get(key);
                }
                catch (SettingsPropertyNotFoundException)
                {
                  // handle bad arguments as you wish
                }
}

Example:

Settings.Default.LoadFrom(new NameValueCollection() { { "Setting1", "Value1" }, { "Setting2", "Value2" } });
1
  • Hm, what exactly was wrong with this one? I don't mind the downvote, but I'd honestly like to know if it's not supposed to work or something.
    – Alan
    Commented Nov 7, 2008 at 20:14
2
votes

Comes in useful for unit testing:

public static IList<T> Clone<T>(this IList<T> list) where T : ICloneable
{
    var ret = new List<T>(list.Count);
    foreach (var item in list)
        ret.Add((T)item.Clone());

    // done
    return ret;
}

A series of these like TWith2Sugars, alternate shortened syntax:

public static long? ToNullableInt64(this string val)
{
    long ret;
    return Int64.TryParse(val, out ret) ? ret : new long?();
}

And finally this - is there something already in the BCL that does the following?

public static void Split<T>(this T[] array, 
    Func<T,bool> determinator, 
    IList<T> onTrue, 
    IList<T> onFalse)
{
    if (onTrue == null)
        onTrue = new List<T>();
    else
        onTrue.Clear();

    if (onFalse == null)
        onFalse = new List<T>();
    else
        onFalse.Clear();

    if (determinator == null)
        return;

    foreach (var item in array)
    {
        if (determinator(item))
            onTrue.Add(item);
        else
            onFalse.Add(item);
    }
}
2
  • You could do that in 2 linq select-where statements. Does that count as BCL?
    – chakrit
    Commented Nov 7, 2008 at 10:39
  • Yes. (Obligatory comment character limit here.)
    – cfeduke
    Commented Nov 7, 2008 at 15:19
2
votes

These extension methods are pretty useful for me when parsing form input before putting into the database

public static int? ToInt(this string input) 
{
    int val;
    if (int.TryParse(input, out val))
        return val;
    return null;
}

public static DateTime? ToDate(this string input)
{
    DateTime val;
    if (DateTime.TryParse(input, out val))
        return val;
    return null;
}

public static decimal? ToDecimal(this string input)
{
    decimal val;
    if (decimal.TryParse(input, out val))
        return val;
    return null;
}
2
votes

GetMemberName allows to get the string with the name of a member with compile time safety.

public static string GetMemberName<T, TResult>(
    this T anyObject, 
    Expression<Func<T, TResult>> expression)
{
    return ((MemberExpression)expression.Body).Member.Name;
}

Usage:

"blah".GetMemberName(x => x.Length); // returns "Length"

It comes together with a non-extension static method if you don't have a instance:

public static string GetMemberName<T, TReturn>(
    Expression<Func<T, TReturn>> expression)
    where T : class
{
    return ((MemberExpression)expression.Body).Member.Name;
}

But the call doesn't look as pretty of course:

ReflectionUtility.GetMemberName((string) s => s.Length); // returns "Length"

You can put it on Codeplex if you want.

2
votes

Two little ones (some people find them silly) that I put in all my projects are:

public static bool IsNull(this object o){
  return o == null;
}

and

public static bool IsNullOrEmpty(this string s){
  return string.IsNullOrEmpty(s);
}

It makes my code so much more fluent..

if (myClassInstance.IsNull()) //... do something

if (myString.IsNullOrEmpty()) //... do something

I think these would make really nice extension properties; if we ever get those.

7
  • 1
    Would this be better? public static bool IsNull<T>(this T obj) where T : class { return (obj == null); }
    – Dan Diplo
    Commented Nov 16, 2009 at 15:12
  • @Dan Diplo I don't think your change would make any difference at all. It make no difference to use generics to compare an object to null.
    – jpbochi
    Commented Jan 12, 2010 at 16:11
  • 2
    The advantage of using generics is this: If you try to call Dan Diplo's generic version of IsNull() on a struct you get a compile-time error. If you call John Kraft's original version it doesn't warn you (and also adds boxing code).
    – Ray Burns
    Commented Feb 4, 2010 at 1:23
  • @Ray Burns You are absolutely correct, however, I consider that to be a plus on mine; it won't throw an exception, and the boxing is the preferred behavior in the code that I am writing. Besides, in the current environment I work in (CRUD line-of-business apps), we never have a need for structs; so it doesn't matter.
    – John Kraft
    Commented Feb 4, 2010 at 22:35
  • 1
    I'm confused at the concern over structs. A struct, by definition, can never be null. Therefor, the fact that it returns false on a struct is correct behavior.
    – John Kraft
    Commented Aug 19, 2011 at 13:20
2
votes

FindControl with built-in casting:

public static T FindControl<T>(this Control control, string id) where T : Control
{
    return (T)control.FindControl(id);
}

It's nothing amazing, but I feel it makes for cleaner code.

// With extension method
container.FindControl<TextBox>("myTextBox").SelectedValue = "Hello world!";

// Without extension method
((TextBox)container.FindControl("myTextBox")).SelectedValue = "Hello world!";

This can be put this in the codeplex project, if so desired

1
  • I would rather use as T instead of casting
    – jpbochi
    Commented Jan 12, 2010 at 15:55
2
votes

I'm using this one quite a lot...

Original code:

if (guid != Guid.Empty) return guid;
else return Guid.NewGuid();

New code:

return guid.NewGuidIfEmpty();

Extension method:

public static Guid NewGuidIfEmpty(this Guid uuid)
{
    return (uuid != Guid.Empty ? uuid : Guid.NewGuid());
}
1
  • Maybe something like... guid.NewGuidIfEmpty(); return guid; ...could be better, semantically speaking. Commented May 14, 2009 at 18:31
2
votes

I have implemented a package of extension methods (available at http://foop.codeplex.com/) and some of my daily used ones are:

// the most beloved extension method for me is Pipe:
<%= variable.Pipe(x => this.SomeFunction(x)).Pipe(y =>
{
    ...;
    return this.SomeOtherFunction(y);
}) %>

var d = 28.December(2009); // some extension methods for creating DateTime
DateTime justDatePart = d.JustDate();
TimeSpan justTimePart = d.JustTime();
var nextTime = d.Add(5.Hours());

using(StreamReader reader = new StreamReader("lines-of-data-file-for-example")) {
    ...
    // for reading streams line by line and usable in LINQ
    var query = from line in reader.Lines(); 
                where line.Contains(_today)
                select new { Parts = PartsOf(line), Time = _now };
}

500.Sleep();

XmlSerialize and XmlDeserialize

IsNull and IsNotNull

IfTrue, IfFalse and Iff:
true.IfTrue(() => Console.WriteLine("it is true then!");

IfNull and IfNotNull
3
  • +1 I particularly liked the Pipe method. I had to download your source to find out that it was like a Where on a single value, though. Could someone edit the answer to make this point clearer?
    – jpbochi
    Commented Jan 12, 2010 at 15:46
  • 'Pipe' is different than 'Where'. 'Where' is a 'map' (in mathematical sense and in functional languages) which takes a set (collection & in .NET case an IEnumerable<T>) & a function (which in .NET land is a delegate and can be represented by a lambda expression like x => x > 2; the only restriction on provided predicate is that it must return a Boolean. 'Pipe' operator is a common tool in functional languages. It's main usage is for chaining computations (function calls). It gets a value & a function (like x => f(x)); then it applies the function to the value & returns the result. Commented Jan 13, 2010 at 22:44
  • 3
    I'm afraid some of these I don't like. 500.Sleep() for example... Just a little too cryptic for my liking. I don't see what's wrong with plain Thread.Sleep()
    – Ian
    Commented Jan 28, 2010 at 9:14
2
votes

This one can be quite useful :

    public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> selector)
    {
        if (first == null)
            throw new ArgumentNullException("first");
        if (second == null)
            throw new ArgumentNullException("second");
        if (selector == null)
            throw new ArgumentNullException("selector");

        using (var enum1 = first.GetEnumerator())
        using (var enum2 = second.GetEnumerator())
        {
            while (enum1.MoveNext() && enum2.MoveNext())
            {
                yield return selector(enum1.Current, enum2.Current);
            }
        }
    }

It has been added to the Enumerable class in .NET 4.0, but it's handy to have it in 3.5.

Example :

var names = new[] { "Joe", "Jane", "Jack", "John" };
var ages = new[] { 42, 22, 18, 33 };

var persons = names.Zip(ages, (n, a) => new { Name = n, Age = a });

foreach (var p in persons)
{
    Console.WriteLine("{0} is {1} years old", p.Name, p.Age);
}
1
  • Beware that argument validation should not reside in the same method as the yield return 's. The problem is that the ArgumentNullException 's will be thrown at the start of iteration of the returned "query". It should have been thrown at the call to the Zip method.
    – jpbochi
    Commented Jan 7, 2010 at 17:03
2
votes

NullPartial HTML helper for ASP MVC.

When passed a null Model, HTML.Partial and HTML.RenderPartial will provide the View's model, if this partial is strongly typed and the View has a different type it will throw an exception rather than passing a null reference. These helpers let you specify two different partials so you can keep your null tests out of the view.

You have permission to include this on the Codeplex page

public static class nullpartials
    {
        public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model)
        {
            if (Model == null)
                return helper.Partial(NullPartial);
            else
                return helper.Partial(Partial, Model);
        }

        public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model, ViewDataDictionary viewdata)
        {
            if (Model == null)
                return helper.Partial(NullPartial, viewdata);
            else
                return helper.Partial(Partial, Model, viewdata);
        }

        public static void RenderNullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model)
        {
            if (Model == null)
            {
                helper.RenderPartial(NullPartial);
                return;
            }
            else
            {
                helper.RenderPartial(Partial, Model);
                return;
            }
        }

        public static void RenderNullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model, ViewDataDictionary viewdata)
        {
            if (Model == null)
            {
                helper.RenderPartial(NullPartial, viewdata);
                return;
            }
            else
            {
                helper.RenderPartial(Partial, Model, viewdata);
                return;
            }
        }
    }
0
2
votes

Reduces the length of a string to toLength and adds an additional string to the end of the shortened string to denote that the string was shortened (Default ...)

public static string Shorten(this string str, int toLength, string cutOffReplacement = " ...")
{
    if (string.IsNullOrEmpty(str) || str.Length <= toLength)
        return str;
    else
        return str.Remove(toLength) + cutOffReplacement;
}
2
  • 2
    Adding " ..." would return ShortenToLength + 4 chars, ie a string longer than what the documentation says.
    – sisve
    Commented Nov 2, 2009 at 18:50
  • @Simon - Fixed the documentation. @peSHIr - I edited it, could you elaborate please.
    – Omar
    Commented Jul 5, 2010 at 16:53
2
votes

I am sure this has been done before, but I find myself using this method (and simpler derivatives) often:

public static bool CompareEx(this string strA, string strB, CultureInfo culture, bool ignoreCase)
{
    return string.Compare(strA, strB, ignoreCase, culture) == 0;
}

You can write it in a number of ways, but I like it because it very quickly unifies my approach to comparing strings while saving me lines of code (or characters of code).

2
votes

My most used extension is one which can format byte arrays:

/// <summary>
/// Returns a string representation of a byte array.
/// </summary>
/// <param name="bytearray">The byte array to represent.</param>
/// <param name="subdivision">The number of elements per group,
/// or 0 to not restrict it. The default is 0.</param>
/// <param name="subsubdivision">The number of elements per line,
/// or 0 to not restrict it. The default is 0.</param>
/// <param name="divider">The string dividing the individual bytes. The default is " ".</param>
/// <param name="subdivider">The string dividing the groups. The default is "  ".</param>
/// <param name="subsubdivider">The string dividing the lines. The default is "\r\n".</param>
/// <param name="uppercase">Whether the representation is in uppercase hexadecimal.
/// The default is <see langword="true"/>.</param>
/// <param name="prebyte">The string to put before each byte. The default is an empty string.</param>
/// <param name="postbyte">The string to put after each byte. The default is an empty string.</param>
/// <returns>The string representation.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="bytearray"/> is <see langword="null"/>.
/// </exception>
public static string ToArrayString(this byte[] bytearray,
    int subdivision = 0,
    int subsubdivision = 0,
    string divider = " ",
    string subdivider = "  ",
    string subsubdivider = "\r\n",
    bool uppercase = true,
    string prebyte = "",
    string postbyte = "")
{
    #region Contract
    if (bytearray == null)
        throw new ArgumentNullException("bytearray");
    #endregion

    StringBuilder sb = new StringBuilder(
        bytearray.Length * (2 + divider.Length + prebyte.Length + postbyte.Length) +
        (subdivision > 0 ? (bytearray.Length / subdivision) * subdivider.Length : 0) +
        (subsubdivision > 0 ? (bytearray.Length / subsubdivision) * subsubdivider.Length : 0));
    int groupElements = (subdivision > 0 ? subdivision - 1 : -1);
    int lineElements = (subsubdivision > 0 ? subsubdivision - 1 : -1);
    for (long i = 0; i < bytearray.LongLength - 1; i++)
    {
        sb.Append(prebyte);
        sb.Append(String.Format(CultureInfo.InvariantCulture, (uppercase ? "{0:X2}" : "{0:x2}"), bytearray[i]));
        sb.Append(postbyte);

        if (lineElements == 0)
        {
            sb.Append(subsubdivider);
            groupElements = subdivision;
            lineElements = subsubdivision;
        }
        else if (groupElements == 0)
        {
            sb.Append(subdivider);
            groupElements = subdivision;
        }
        else
            sb.Append(divider);

        lineElements--;
        groupElements--;
    }
    sb.Append(prebyte);
    sb.Append(String.Format(CultureInfo.InvariantCulture, (uppercase ? "{0:X2}" : "{0:x2}"), bytearray[bytearray.LongLength - 1]));
    sb.Append(postbyte);

    return sb.ToString();
}

By default ToArrayString() just prints the byte array as a long string of individual bytes. However, ToArrayString(4, 16) groups the bytes in groups of four, with 16 bytes on a line, just as it is in your favorite hex editor. And the following nicely formats the byte array for usage in C# code:

byte[] bytearray = new byte[]{ ... };
Console.Write(bytearray.ToArrayString(4, 16, ", ", ",   ", ",\r\n", true, "0x"));

It was written by me, so you may put it on Codeplex.

1
  • Wow, 8 parameters (not counting the this parameter) ! IMHO, any method with more than 4 parameters needs refactoring... Commented Aug 19, 2010 at 19:14
2
votes

Inspired by String.IsNullOrEmpty

To validate the given List is null or empty

public static bool IsNullOrEmpty<TSource>(this List<TSource> src)
{            
    return (src == null || src.Count == 0);
}

And this one is to validate given 2 files and properties

public static bool Compare(this FileInfo f1, FileInfo f2, string propertyName)
{
    try
    {
        PropertyInfo p1 = f1.GetType().GetProperty(propertyName);
        PropertyInfo p2 = f2.GetType().GetProperty(propertyName);

        if (p1.GetValue(f1, null) == p2.GetValue(f1, null))
            return true;
    }
    catch (Exception ex)
    {
        return false;
    }
    return false;
}

And use it like this

FileInfo fo = new FileInfo("c:\\netlog.txt");
FileInfo f1 = new FileInfo("c:\\regkey.txt");

fo.compare(f1, "CreationTime");
6
  • Could be extende to be more generic, too public static bool CompareByProperty<Tself, Tother>(this Tself self, Tother other, string propertyName) but you will have to change the comparison to use Equals(value1, value2) instead of == since == compares the reference for object types: stackoverflow.com/questions/814878/… Commented Oct 14, 2010 at 12:02
  • 7
    Why not an IsNullOrEmpty<T>() that accepts an IEnumerable<T>?
    – jpbochi
    Commented Oct 14, 2010 at 13:20
  • 5
    By the way, you lost my vote up by appending that ? true : false.
    – jpbochi
    Commented Oct 14, 2010 at 13:22
  • 1
    This should be split into two separate answers. The first one is ok (should be IEnumerable<T> instead of List<T>). The second is dubious. I agree with @SchlaWiener, make it generic. I'd also lose the catch. If an exception is thrown, let the caller decide how to handle it.
    – Greg
    Commented Oct 14, 2010 at 15:23
  • 1
    The IsNullOrEmpty method is a good idea, I use it all the time (but with IEnumerable<T>, not List<T>)... but I'm pretty sure it has already been posted. Regarding the second method, I see no reason to restrict it to FileInfo. Also, passing a string with the property name is a bad idea: you can do the same with a delegate, and you avoid the overhead of reflection Commented Oct 14, 2010 at 20:18
2
votes

For raising events concisely:

public static void Raise(this EventHandler handler, object sender, EventArgs e)
{
    if (handler != null)
    {
        handler(sender, e);
    }
}

public static void Raise<T>(this EventHandler<T> handler, object sender, T e) where T : EventArgs
{
    if (handler != null)
    {
        handler(sender, e);
    }
}

Usage:

public event EventHandler Bar;

public void Foo()
{
    Bar.Raise(this, EventArgs.Empty);
}

There's a bit of discussion about potential thread-safety issues here. Since .NET 4, the above form is thread-safe, but requires rearranging and some locks if using an older version.

5
  • There is an issue with this solution: you can only use it if the event is declared in the current class, not if it's declared in a base class... Commented Oct 15, 2010 at 9:34
  • @Thomas: Isn't the same is true for raising events manually? The solution is to use the protected virtual void OnBar(Eventargs e) pattern outlined here: msdn.microsoft.com/en-us/library/hy3sefw3%28VS.80%29.aspx. Commented Oct 15, 2010 at 12:09
  • Yes, but what I mean is that your solution doesn't work in the general case Commented Oct 15, 2010 at 12:38
  • Actually, this is thread-safe in older versions too. I've written identical methods myself.
    – SLaks
    Commented Oct 15, 2010 at 19:23
  • +1 - I generally hate extension methods for Null objects; however, this is a really nice usage! Commented Oct 25, 2010 at 17:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.