53

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
{

}
0

7 Answers 7

103

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.

Sign up to request clarification or add additional context in comments.

Comments

26

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)
        

Comments

21

.Net V 4.6 OR C # 6.0

Try This

 if (Attachment?.Length > 0)

2 Comments

Maybe in 5 years our systems will recognize it... in my 4.6 framework project it's still compiles as an error.
@HellBaby then you need to check the language associated with your project. Just because you are using DotNet 4.6 doesn’t mean that you are using C# >= 6. You could still be using C#5 for all you know. Go into your project's settings: right-click on project -> Properties -> Build -> Advanced and set the language explicitly to C# >= 6.
10

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.

2 Comments

Thanks Thanks Thanks Habib....So much. but can you tell me what a issue with previous one plz
@SANDEEP, just modified the answer, for why you were getting the exception before
4

The best if statement in my opinion is this:

if(Attachment  is { Length: > 0 })

this code check both: null and length of the attachment

Comments

0

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.

1 Comment

Yes, but .Any() is not internal method and adds a dependency to System.Linq (LINQ) library. LINQ is great, but for this simple action I wouldn't add an extra dependency.
0

In Android Studio version 3.4.1

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

1 Comment

The question was for C#. See the tag at bottom... ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.