views:

77

answers:

4

Can I put an object.property which hasn't been instantiated on the right hand side of an 'AND' operator if I know that the left hand side will fail but if the left side passes the right side will be instantiated?

In the example below the first if/else statement sets up the other if statement for the above question. Although I've tested that it doesn't show errors, I was wondering what happens behind the scenes or is there a better way.(there are many if/else statements that use the results of the first if/else statement.

        if (_articleGuid.Equals(Guid.Empty))
        {
            isArticleGuid = false;
        }
        else
        {
            article = new Article(Guid.Empty, _articleGuid);
            bodyText = article.Text;
            articleDate = Convert.ToDateTime(article.DateActive);

            isArticleGuid = true;
        }

        if(isArticleGuid && article.Author != null)
        {
            divAuthor.InnerText = article.Author;                        
        }
+4  A: 

Assuming I understand you correctly, this is safe. The article variable will need to be definitely assigned, but the language guarantees that if the LHS expression of an && operator evaluates to false, the RHS expression won't be evaluated - so you're not going to get a NullReferenceException.

From the C# 3.0 language specification, section 7.11:

The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is not false.

Jon Skeet
Thats correct I don't get any errors and hoped it wasn't bad coding practise to do it this way otherwise its extra if statements eg if(isArticleGuid)....if(article.Author != null)
insanepaul
No, it's absolutely fine to rely on this.
Jon Skeet
+2  A: 

Yes, that is fine because the && operator is guaranteed to be short-circuiting.

To be more safe you could check that article is not null instead of / as well as checking isArticleGuid.

Mark Byers
+2  A: 

In C#, the logical and operator && evaluates its arguments from left to right and uses short circuit evaluation. That means that if the first argument evaluates to false then the second will never be evaluated.

Using this isn't bad coding practice - it's an well known idiom common to many languages with C style syntax (C, C++, C#, D, etc)

Joe Gauterin
A: 

Just as a aside, and further to Jon's answer, VB .Net can also do short-circuit evaluation with the new (and ugly, IMO) 'AndAlso' and 'OrElse' keywords.

If SomeRef IsNot Null AndAlso SomeRef.Property = 42 Then
...etc
Gareth Wilson