Comparing Bytes

January 3rd, 2010

While preparing for another post (coming soon), I ran across the need to compare two arrays of bytes.  I’ve done this in the past, but when I started poking around I realized that I had forgotten that there was only a manual method of doing so… that is until .NET 3.5!  You can now use LINQ’s SequenceEqual extension method:

   1: using System.Linq;

   2:  

   3: namespace CompareBytes

   4: {

   5:     class Program

   6:     {

   7:         static void Main(string[] args)

   8:         {

   9:             var foo = new byte[] {1, 2};

  10:             var bar = new byte[] {1, 2, 3};

  11:  

  12:             var isEqual = foo.SequenceEqual(bar);

  13:  

  14:             ...

  15:         }

  16:     }

  17: }

 

Note that you can use this extension method for any other sequence comparisons (including custom objects – you’ll need to implement IEqualityComparer<T> in your custom class).

Go forth and compare manually no longer!

Sean Timm Esoterica

  1. January 4th, 2010 at 00:56 | #1

    Atleast MSTEST and NUnit have a class CollectionAssert with an AreEqual method which does teh following: Verifies that specified collections are equal. Two collections are equal if they have the same elements in the same order and quantity. Elements are equal if their values are equal, not if they refer to the same object.

    • January 4th, 2010 at 01:42 | #2

      True, Tim. In my case, I needed to do the comparison inside of production code, so shipping the test assemblies wouldn’t be an option. :) Definitely the way to go for unit tests, though.

  1. No trackbacks yet.