Tomas
Tomas

Reputation: 18097

How to find empty bytes array

How to find out is bytes array has any data or it is newly created bytes array?

var Buffer = new byte[1000];
//How to find out is Buffer is empty or not?

Upvotes: 1

Views: 6278

Answers (3)

Metin Atalay
Metin Atalay

Reputation: 1517

In addition to the answers given

            var buffer = new byte[1000];
            var bFree = true;
            foreach (var b in buffer)
            {
                if (b == default(byte)) continue;
                bFree = false;
                break;
            }

Upvotes: 0

sehe
sehe

Reputation: 392843

A byte is a valuetype, it cannot be null;

Creating an array immediately initializes the elements to the default value for the element type.

This means, empty cells can't exist, let alone be detected.

If you must:

  1. use nullable types

    var Buffer = new byte?[1000];

  2. use Array.Resize when capacity changes. However, you could soon be in a situation where just using a System.Collections.Generic.List would be much more efficient

Upvotes: 1

George Duckett
George Duckett

Reputation: 32428

I assume by 'empty' you mean containing default values for every byte element, if this isn't what you mean, look at @sehe's answer.

How about using LINQ to check whether all elements have the default value for the type:

var Empty = Buffer.All(B => B == default(Byte));

Upvotes: 7

Related Questions