Walter Zydhek
Walter Zydhek

Reputation: 293

How can I convert a function to be a generic tempate

I have a function that I would like to use generics with I assume. Instead of the int[] in the function below, I would like the function to work with an array of pretty much any type (such as int[], double[], string[] etc..). How can I modify this code to do that?

    public static bool isHomogenous(int[] list)
    {
        bool result = true;
        for (int i = 0; i < list.Length; i++)
            if (list[i] != list[0])
                result = false;
        return result;
    }

Upvotes: 0

Views: 28

Answers (2)

wingerse
wingerse

Reputation: 3796

The answer above also works but here is a shorter version:

public static bool IsHomogenous<T>(T[] list)
{
    return !list.Distinct().Skip(1).Any();
}

Upvotes: 0

ryanyuyu
ryanyuyu

Reputation: 6486

Use a generic method signature. By convention, the type specifier is prefixed with T.

public static bool isHomogenous<T>(T[] list)
{
    bool result = true;
    for (int i = 0; i < list.Length; i++)
        if (!list[i].Equals(list[0]))
            result = false;
    return result;
}

Note that this treats the generic type T as an object if you don't constrain it with where, so you'll have to use the .Equals method to compare the values.

Alternatively, just use LINQ:

public static bool IsHomogenousLinq<T>(IEnumerable<T> list)
{
    //handle null and empty lists however you want (throw ArgEx?, return false?)
    var firstElement = list.First();
    return list.All(element => element.Equals(firstElement));
}

Demo on .NET Fiddle

Upvotes: 1

Related Questions