Nullable DateTime with HasValue check

Please take a look at the underneath code:

1.     DateTime? startDate = SomeMethod();

2.     if (startDate.HasValue)

3.     {

4.          DoSomething();

5.     }

ReSharper says with constructions like this: "Expression is always true" for line 2. Why is this? Looks like a bug to me.

4 comments
Comment actions Permalink

FWIW, code below works fine with 5.1.1753 (no "is always true" warning).

class Foo
    {
        DateTime? GetDate()
        {
            return null;
        }

        void Bar()
        {
            DateTime? date = GetDate();
            if (date.HasValue)
                throw new InvalidOperationException();
            throw new ApplicationException();
        }
    }
0
Comment actions Permalink

Hello Marino,

I couldn't reproduce this behavior either. Could you please attach a small
sample solution demonstrating this problem? Thank you!

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

DateTime? startDate = SomeMethod();
2.     if (startDate.HasValue)
3.     {
4.          DoSomething();
5.     }



0
Comment actions Permalink

Are you sure SomeMethod() returns "DateTime?"? If it returns DateTime only the result will never be null and Resharper is correct.

0
Comment actions Permalink

I guess this was the thing that went wrong.

(Sorry for the late(!) reply, apparently I don't get mail if people reply. Shall configure immediately ;) )

0

Please sign in to leave a comment.