Some extensions methods that I like

String extensions

public static class StringExtensions
{
    public static string F(this string text, params object[] args)
    {
        return string.Format(text, args);
    }
}

This extension method is very clear and doesn't need explanation, usage:

"Hello, my name is {0}".F("Jose")

Int extensions

public static class IntExtensions
{
    public static IEnumerable<int> To(this int start, int end)
    {
        return Enumerable.Range(start, end);
    }
}

1.To(10) will returns an IEnumerable with elements from 1 to 10

Cast extension

public static class CastsExtensions
{
    public static T To<T>(this object o)
    {
        return (T)o;
    }

    public static T As<T>(this object o) where T : class
    {
        return o as T;
    }
}

This is self descriptive too. It allows you to cast and access a property with a more cleaner syntax: someObject.To<IDataErrorInfo>().Errors

Datetime extensions

public static class DateTimeExtensions
{
    public static DateTime FromNow(this TimeSpan self)
    {
        return DateTime.Now.Add(self);
    }
    public static DateTime From(this TimeSpan self, DateTime dateTime)
    {
        return dateTime.Add(self);
    }
    public static TimeSpan Days(this int days)
    {
        return TimeSpan.FromDays(days);
    }
}

I really like this extension method:

10.Days().FromNow()
    .Should().Be.EqualTo(DateTime.Today.AddDays(10));

10.Days().From(new DateTime(2009, 10, 10))
    .Should().Be.EqualTo(new DateTime(2009, 10, 20));

Enumerable extensions

public static class EnumerableExtensionsMethods
{
    public static void ForEach<T>(
            this IEnumerable<T> enumerable, 
            Action<T> action)
    {
        foreach (T item in enumerable)
        {
            action(item);
        }
    }
}

But, I already explained this in this post.


blog comments powered by Disqus
  • Categories

  • Archives