Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an existing library of extension methods for C#? or share your own [duplicate]

Possible Duplicate:
Post your extension goodies for C# .Net (codeplex.com/extensionoverflow)

I'm fond of C# 3.0. One of my favorite parts is extension methods.

I like to think of extension methods as utility functions that can apply to a broad base of classes. I am being warned that this question is subjective and likely to be closed, but I think it's a good question, because we all have "boilerplate" code to do something relatively static like "escape string for XML" - but I have yet to find a place to collect these.

I'm especially interested in common functions that perform logging/debugging/profiling, string manipulation, and database access. Is there some library of these types of extension methods out there somewhere?

Edit: moved my code examples to an answer. (Thanks Joel for cleaning up the code!)

like image 663
Jeff Meatball Yang Avatar asked May 28 '09 21:05

Jeff Meatball Yang


2 Answers

You might like MiscUtil.

Also, a lot of people like this one:

public static bool IsNullOrEmpty(this string s)
{
    return s == null || s.Length == 0;
}

but since 9 times out of 10 or more I'm checking that it's not null or empty, I personally use this:

public static bool HasValue(this string s)
{
    return s != null && s.Length > 0;
}

Finally, one I picked up just recently:

public static bool IsDefault<T>(this T val)
{
    return EqualityComparer<T>.Default.Equals(val, default(T));
}

Works to check both value types like DateTime, bool, or integer for their default values, or reference types like string for null. It even works on object, which is kind of eerie.

like image 136
Joel Coehoorn Avatar answered Sep 20 '22 19:09

Joel Coehoorn


Here's a couple of mine:

// returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
public static double UnixTicks(this DateTime dt)
{
    DateTime d1 = new DateTime(1970, 1, 1);
    DateTime d2 = dt.ToUniversalTime();
    TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
    return ts.TotalMilliseconds;
}

and a ToDelimitedString function:

// apply this extension to any generic IEnumerable object.
public static string ToDelimitedString<T>(this IEnumerable<T> source, string delimiter, Func<T, string> action)
{
    if (source == null)
    {
        throw new ArgumentException("Source can not be null.");
    }

    if (delimiter == null)
    {
        throw new ArgumentException("Delimiter can not be null.");
    }

    string strAction = string.Empty;
    string delim = string.Empty;
    var sb = new StringBuilder();

    foreach (var item in source)
    {
        strAction = action.Invoke(item);

        sb.Append(delim);
        sb.Append(strAction);
        delim = delimiter;
    }
    return sb.ToString();
}
like image 28
Jeff Meatball Yang Avatar answered Sep 18 '22 19:09

Jeff Meatball Yang