Reputation: 1082
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
{
}
Upvotes: 53
Views: 168116
Reputation: 798
The best if statement in my opinion is this:
if(Attachment is { Length: > 0 })
this code check both: null and length of the attachment
Upvotes: 4
Reputation: 109567
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)
Upvotes: 26
Reputation: 646
In Android Studio version 3.4.1
if(Attachment != null)
{
code here ...
}
Upvotes: 0
Reputation: 1124
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.
Upvotes: 0
Reputation: 98750
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.
Upvotes: 102
Reputation: 223257
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
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.
Upvotes: 10