Memcmp in C#


I confess that, for some years now, I’ve wondered what the managed equivalent of memcmp() was, usually when I wanted to compare two byte arrays for equality. It turns out that Linq provides a SequenceEquals() extension method which does exactly what I want:


using System;
using System.Linq;


namespace SequenceEquals
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] a = new byte[] { 1, 2, 3 };
            byte[] b = new byte[] { 4, 5, 6 };
            byte[] c = new byte[] { 1, 2, 3 };
            byte[] d = new byte[] { 1, 2 };


            Console.WriteLine(“{0}”, a.SequenceEqual(a));
            Console.WriteLine(“{0}”, a.SequenceEqual(b));
            Console.WriteLine(“{0}”, a.SequenceEqual(c));
            Console.WriteLine(“{0}”, a.SequenceEqual(d));
        }
    }


The code above gives True, False, True, False.


Comments (2)

  1. phrosty@gmail.com says:

    Mono.Rocks also has a .SequenceCompare() extension method which does a lexicographical compare.

  2. MichaelGG says:

    Wow, I could have sworn Array or Buffer or something had some fast method for this. Wierd.

    Anyways, as you probably know, I’d imagine performance will suck. Unlike some of the Enumerable methods, SequenceEquals doesn’t have a fast path for arrays or ILists.