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.
You haven’t added functionality that is only useful to a specific application or context, your extension is clearly named and the behaviour is obvious without having to look at the implementation.
The answer is ‘Yes, it is’