NullReferenceException syntax

Hi,

One question more using ReSharper 5.1. Suppose I haven this code:

if (this.GetType().BaseType != null)
     Debug.Write(this.GetType().BaseType.BaseType);

With this I get a "NullReferenceException" warning from ReSharper.

However if I do this:

var baseType = this.GetType().BaseType;
if (baseType != null)
     Debug.Write(baseType.BaseType);

There is no problems. Why does the first example give me a warning whilst the second doesn't?

--

Werner'

2 comments
Comment actions Permalink

Hello Werner,

The first example involves a method call and a property invocation. ReSharper
cannot make sure that this.GetType().BaseType will return exactly the same
value (or a not-null value) both times it's invoked and therefore marks the
second call with possible NullReferenceException. In the second example,
the value of this.GetType().BaseType is saved in a local variable and ReSharper
can make sure that the value of the variable doesn't change between the null
check and the usage. Thank you!

Andrey Serebryansky
Senior Support Engineer
JetBrains, Inc
http://www.jetbrains.com
"Develop with pleasure!"

Hi,

One question more using ReSharper 5.1. Suppose I haven this code:

if (this.GetType().BaseType != null)
Debug.Write(this.GetType().BaseType.BaseType);
With this I get a "NullReferenceException" warning from ReSharper.
However if I do this:

var baseType = this.GetType().BaseType;
if (baseType != null)
Debug.Write(baseType.BaseType);
There is no problems. Why does the first example give me a warning
whilst the second doesn't?

--
Werner'
---
Original message URL:
http://devnet.jetbrains.net/message/5276496#5276496



0
Comment actions Permalink

Makes sense mostly, thanks.

0

Please sign in to leave a comment.