I just wrote an if statement in the lines of
if (value == value1 || value == value2 || value == value3 || value == value4)
//do something
and it annoys me that I always have to repeat the 'value ==' part. In my opinion this is serving no purpose other than making it difficult to read.
I wrote the following ExtensionMethod that should make above scenario more readable:
public static bool IsEqualToAny<T>(this T value, params T[] objects)
{
return objects.Contains(value);
}
Now I can simply write
if (value.IsEqualToAny(value1, value2, value3, value4))
//do something
Is this a good usage of an ExtensionMethod?
EDIT:
Thanks for all the great answers. For the record: I have kept the method. While the suggestion that you could simply use new []{value1,value2,value3,value4}.Contains(value)
is true, I simply prefer reading this kind of if statement from left to right (if this value is equal to any of these instead of if these values contain this value). Having one more method show up in intellisense on each object is not an issue for me.
Adding extension methods to any type is a great way to improve productivity and simplify code.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.
An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.
It is unusual to write an extension method for an unrestricted T
. Not least, this approach will quickly make your intellisense quite hard to use.
While valid, I'd probably avoid this as an extension method - perhaps just use a standard static utility method.
The C# 3 array initializer syntax might be easier?
bool isTrue = new[] { 1, 2, 3 }.Contains(3);
Of course, for large sets of data, you might want to cache a HashSet<T>
somewhere ;-p
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With