Skip to content

Instantly share code, notes, and snippets.

@sergiopereira
Created April 26, 2010 19:28
Show Gist options
  • Save sergiopereira/379769 to your computer and use it in GitHub Desktop.
Save sergiopereira/379769 to your computer and use it in GitHub Desktop.
// Instead of writing:
// if( a == "abc" || a == "xyz" || a == "123" ) { ... }
// if( opt != Options.Opt1 && opt != Options.Opt2 && opt != Options.Opt3 ) { ... }
// We can write:
// if( a.OneOf("abc", "xyz", 123") ) { ... }
// if( opt.NoneOf(Options.Opt1, Options.Opt2, Options.Opt3) ) { ... }
public static class ObjectExtensions
{
public static bool OneOf<T>(this T self, params T[] values)
{
return !IsNull(self) && values.Any(value => self.Equals(value));
}
public static bool NoneOf<T>(this T self, params T[] values)
{
return !IsNull(self) && !self.OneOf(values);
}
private static bool IsNull<T>(T self)
{
object def = default(T);
return def == null && object.Equals(self, def);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment