How to determine if three ints are all equal

I modified my original answer to include a method that is more general purpose and that does not rely on LINQ or extension methods. I think it's safe to assume this method would be more performant based on the fact that it doesn't have to enumerate the entire list to determine uniqueness when there are values that are different early on in the list.

class Program 
{ 
    static void Main(string[] args) 
    { 
        int value1 = 1, value2 = 2, value3 = 1; 
        Console.WriteLine(AllAreEqual<int>(value1, value2, value3));

        Console.Write("V2: 1 value ");
        Console.WriteLine(AllAreEqual_V2<int>(1));

        Console.Write("V2: no value ");
        Console.WriteLine(AllAreEqual_V2<int>());

        Console.Write("V2: 3 values, same ");
        Console.WriteLine(AllAreEqual_V2<int>(1, 1, 1));

        Console.Write("V2: 3 values, different ");
        Console.WriteLine(AllAreEqual_V2<int>(1, 1, 2));

        Console.Write("V2: 2 values, same ");
        Console.WriteLine(AllAreEqual_V2<int>(1, 1));

        Console.Write("V2: 2 values, different ");
        Console.WriteLine(AllAreEqual_V2<int>(1, 2));

        Console.ReadKey(); 
    } 

    static bool AllAreEqual<T>(params T[] args) 
    { 
        return args.Distinct().ToArray().Length == 1; 
    }

    static bool AllAreEqual_V2<T>(params T[] args)
    {
        if (args.Length == 0 || args.Length == 1)
        {
            return true;
        }

        if (args.Length == 2)
        {
            return args[0].Equals(args[1]);
        }

        T first = args[0];

        for (int index = 1; index < args.Length; index++)
        {
            if (!first.Equals(args[index]))
            {
                return false;
            }
        }

        return true;
    }
}

The second seems just fine to me.

As the list gets longer, that could get unwieldy. In which case I'd write an extension method along the lines of AllSame.

bool AllSame(this IEnumerable<int> list)
{
    bool first = true;
    int comparand = 0;
    foreach (int i in list) {
       if (first) comparand = i;
       else if (i != comparand) return false;
       first = false;
    }
    return true;
}

or use the params keyword:

bool AllSame(params int[] list)
{
    return (list as IEnumerable<int>).AllSame();
}

Then you can just write:

if (AllSame(value1, value2, value3, value4, value5)) ...

That seems fine to me. The only comment I have is that you should introduce an 'explaining variable' for the equation. Besides explaining the calculation, the return now provides a nice place for a breakpoint or a tracepoint when inspecting the result.

bool allThreeAreEqual = value1 == value2 && value2 == value3;
return allThreeAreEqual;

Tags:

C#