public IsFree(byte[] Raw) { if (Raw == null) return true; foreach (byte b in Raw) if (b != 0xFF) return false; return true; } 

Is it possible to make the check shorter / more beautiful? The void is exactly 0xFF

  • 2
    in Linq for example, there is an all method for enumeration. more introductory! PS: better isEmpty name - teran
  • If the length of the Raw array is small and the maximum size is known, you can create a second array filled with 0xFF, and use the WinAPI call RtlEqualMemory for comparison. - Lunar Whisper
  • Just in order of perversion, you can stick an assembler insert with a call repe scasb or repne scasb , perhaps there is a WinAPI wrapper over it. But this is more about performance than about length. - Lunar Whisper

1 answer 1

 var bytes = new byte[] { /*...*/ }; if (bytes.IsEmpty()) { //.. } public static class BytesExtensions { public static bool IsEmpty(this byte[] source, byte value = 0xFF) { return source == null || source.All(x => x == value); } } 
  • 2
    A very bad decision only because of the use of the default value. The extension method, which will be available throughout the project, with the name IsEmpty () without parameters never matches the implementation and misleads the user. - Lunar Whisper
  • 2
    public bool IsEmpty => (Raw == null || Raw.All (b => b == 0xFF)); // like this I did - Kto To
  • one
    @KtoTo bool IsEmpty = Raw?.All(b => (b==0xFF))??false; - Alias
  • 2
    @Alias, will bool IsEmpty = Raw?.All(x => x==0xFF)??true; - pavelip
  • one
    @Alias ​​is so prettier and more minimal, but harder to read. So much more complicated that he himself made a mistake - Kto To