John Smith
John Smith

Reputation: 1793

Making extension class generic

I have such a piece of code:

using System.Collections.Generic;
using System.Linq;

namespace PricingCoefficientService.Extensions
{
    public static class IntExt
    {
        public static bool IsIn(this int integer, IEnumerable<int> collectionOfIntegers)
        {
            return collectionOfIntegers.Contains(integer);
        }
    }
}

it is an extension method extending int. I believe its functionality is obvious.

But what if I dont want to make it generic to make it usable for each value type or object?

any idea?

thank you

Upvotes: 0

Views: 64

Answers (3)

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

Try this code:

public static bool IsIn<T>(this T generic, IEnumerable<T> collection)
{
    if(collection==null || collection.Count()==0) return false; // just for sure
    return collection.Contains(generic);
}

it is typed by T which can be any type, now you can write:

var list = new List<double>() {1,2,3,4};
double a = 1;
bool isIn = a.IsIn(list);

Upvotes: 1

Alireza
Alireza

Reputation: 10476

If only value types are desired

public static bool IsIn(this ValueType integer, IEnumerable<int> collectionOfIntegers)
{
....
}

Upvotes: 1

Alessandro D&#39;Andria
Alessandro D&#39;Andria

Reputation: 8868

Just make the method generic

public static bool IsIn<T>(this T value, IEnumerable<T> collection)
{
    if (collection == null)
    {
        throw new ArgumentNullException("collection");
    }

    return collection.Contains(value);
}

Upvotes: 2

Related Questions