Thursday, February 14, 2008

Compare Byte Arrays

Slightly more efficient by starting off with a reference compare. If the same two arrays are passed in, no need to compare the elements. I don't think there is a better way unless you use unsafe code / pointers. The use of generics makes this more general purpose.

bool Compare<T>(T[] left, T[] right)

{

    // handles the same array

    // handles both null

    if (left == right)

        return true;

 

    // fails when either are null

    if (left == null || right == null)

        return false;

 

    if (left.Length != right.Length)

        return false;

 

    for (int i = 0; i < left.Length; i++)

    {

        if (!left[i].Equals(right[i]))

            return false;

    }

 

    return true;

}

 

No comments:

Post a Comment