[c#] How to Check byte array empty or not?

I am downloading the word file for GetSourceAttachment method. When this method returns empty bytes then my byte Attachment array gives an error:

Object reference not set instance of object

It gives the error when I check the length of Attachment in if condition.

Can any one help me to default initialize the byte array, then check the length?

try
{
        byte[] Attachment = null ;

        string Extension = string.Empty;
        ClsPortalManager objPortalManager = new ClsPortalManager();
        Attachment = objPortalManager.GetSourceAttachment(Convert.ToInt32(hdnSourceId.Value), out Extension);
        if (Attachment.Length > 0 && Attachment != null)
        {
            DownloadAttachment("Attacment", Attachment, Extension);
        }
        else
        {
            ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Attachment is not Uploaded !');</script>");
        }            
}
catch
{

}

This question is related to c#

The answer is


Now we could also use:

if (Attachment != null  && Attachment.Any())

Any() is often easier to understand in a glance for the developer than checking Length() > 0. Also has very little difference with processing speed.


In Android Studio version 3.4.1

if(Attachment != null)
{
   code here ...
}

.Net V 4.6 OR C # 6.0

Try This

 if (Attachment?.Length > 0)

Your check should be:

if (Attachment != null  && Attachment.Length > 0)

First check if the Attachment is null and then lenght, since you are using && that will cause short-circut evaluation

&& Operator (C# Reference)

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

Previously you had the condition like: (Attachment.Length > 0 && Attachment != null), since the first condition is accessing the property Length and if Attachment is null, you end up with the exception, With the modified condition (Attachment != null && Attachment.Length > 0), it will check for null first and only moves further if Attachment is not null.


You must swap the order of your test:

From:

if (Attachment.Length > 0 && Attachment != null)

To:

if (Attachment != null && Attachment.Length > 0 )

The first version attempts to dereference Attachment first and therefore throws if it's null. The second version will check for nullness first and only go on to check the length if it's not null (due to "boolean short-circuiting").


[EDIT] I come from the future to tell you that with later versions of C# you can use a "null conditional operator" to simplify the code above to:

if (Attachment?.Length > 0)