Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a good use of an ExtensionMethod?

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.

like image 435
Patrick Klug Avatar asked Feb 11 '09 09:02

Patrick Klug


People also ask

Are extension methods good?

Adding extension methods to any type is a great way to improve productivity and simplify code.

What is the use of extension method?

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.

What is an advantage of using extension methods?

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.

What are extension methods explain with an example?

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.


1 Answers

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

like image 69
Marc Gravell Avatar answered Oct 21 '22 02:10

Marc Gravell