Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Check byte array empty or not?

Tags:

c#

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 {  } 
like image 301
SANDEEP Avatar asked May 10 '13 06:05

SANDEEP


People also ask

How do I check if a string array is empty?

To check if an array contains an empty string, call the includes() method passing it an empty string - includes('') . The includes method returns true if the provided value is contained in the array and false otherwise.

What is an empty byte?

In general Java terminology, an empty byte array is a byte array with length zero, and can be created with the Java expression new byte[0] .

How many bytes is a empty char?

It's 18 bytes: 16 bytes of memory + 2 bytes per character allocated + 2 bytes for the final null character.

Can byte be null C#?

If the C# language designers wanted the byte type to be nullable, they'd have to pick a value from the range and elect it as the null value. Let's imagine they picked zero as the null value for byte . If that was the case, we wouldn't be able to use zero as a valid value never again!


2 Answers

Just do

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

From && Operator

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

like image 127
Soner Gönül Avatar answered Oct 15 '22 16:10

Soner Gönül


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)          
like image 29
Matthew Watson Avatar answered Oct 15 '22 16:10

Matthew Watson