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 { }
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.
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] .
It's 18 bytes: 16 bytes of memory + 2 bytes per character allocated + 2 bytes for the final null character.
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!
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With