6

I have a rule in resharper to find calls to Nullable.HasValue

T? foo; 
//...

if(foo.HasValue)
{}

//And it offers to replace with a comparison directly with null:

if(foo != null)
{}

This works great, but when it encounters a negated .HasValue, the result is a little strange.

if(!foo.HasValue) {}

//is replaced with
if(!(foo != null)) {}

Then resharper wants me to simplify the statement to just if(foo == null)

//ideally it would automatically get to this without the extra step:
if(foo == null) {}

The rule is defined as:

type:     System.ValueType or derived
nullable: expression of type System.Nullable<$type$>

search pattern:
$nullable$.HasValue

replace pattern:
$nullable$ != null

('Format after replace' and 'Shorten references' are both checked)

Is there a way I can write this rule so ReSharper handles it intelligently? I tried making a second rule for !$nullable$.HasValue, but that causes both rules to match which makes tool-tip suggestions look confusing: replace with == null and replace with != null.

dan
  • 9,712
  • 6
  • 49
  • 62
  • I don't know a solution. Just an idea and I guess you thought already about it: Remove pattern for `!foo.HasValue` and add only patterns for `foo.HasValue` and `!(foo != null)`. So there is only one rule at a time but unfortunately you need to use **two** consecutive patterns for code like `!foo.HasValue`. – thersch Jul 26 '12 at 08:13
  • Search patterns contain only positive rules. I already missed several times the possibility to define negative rules to exclude special code for a pattern. – thersch Jul 26 '12 at 08:17
  • Resharper Custom Patterns are quite a pain to work out, I wish there was a test custom pattern engine you could run some known good and known bad expressions against inside there – Maslow Jan 10 '13 at 14:28

1 Answers1

0

If is not really mandatory you can give up on this rule because, according to this post:

"The compiler replaces null comparisons with a call to HasValue, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues."

Community
  • 1
  • 1
lex87
  • 1,276
  • 1
  • 15
  • 33
  • 1
    Understood, but my motivation is that I think null comparisons are more readable, and I want resharper to enforce that style decision. – dan Aug 30 '12 at 12:44