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;
}
Assuming I understand you correctly, this is safe. The
articlevariable 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 aNullReferenceException.From the C# 3.0 language specification, section 7.11: