For my first real post I thought I would kick off with something light. I was writing some code recently and realized that the code readability would benefit from two simple extension methods, In<> and Between<>.
I often find myself writing code along the lines of
if (x >= 0 && x <= 10) ...
or
if (new[] {1,2,3}.Contains(x)) ...
So I thought I would throw two extension methods at the problem, I was looking for something that would give me the following syntax.
if (x.Between(0, 10)) ...
and
if (x.In(1,2,3)) ...
The result of my first attempt is the code below, note there are a few overloads to support various alternatives and customizing the comparison.
using System;
using System.Linq;
using System.Collections.Generic;
namespace DotNetWarrior
{
public static class ExtensionMethods
{
public static bool In<T>(this T value, params T[] values)
{
return ExtensionMethods.In(value, null, values);
}
public static bool In<T>(this T value, IEqualityComparer<T> comparer, params T[] values)
{
return In(value, comparer, values as IEnumerable<T>);
}
public static bool In<T>(this T item, IEnumerable<T> values)
{
return In(item, null, values);
}
public static bool In<T>(this T value, IEqualityComparer<T> comparer, IEnumerable<T> values)
{
return values.Contains(value, comparer);
}
public static bool Between<T>(this T item, T min, T max)
{
return ExtensionMethods.Between(item, null, min, max);
}
public static bool Between<T>(this T item, IComparer<T> comparer, T min, T max)
{
if (comparer == null)
{
comparer = Comparer<T>.Default;
}
if (comparer.Compare(min, max) == 1) throw new ArgumentException("min must be less than or equal to max.");
return (comparer.Compare(item, min) >= 0) && (comparer.Compare(item, max) <= 0);
}
}
}
Well, I hope you find this useful. Till I blog again.
No comments:
Post a Comment