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!


