Reputation: 293
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
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
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));
}
Upvotes: 1