Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between bool? MyProperty and bool ?MyProperty

Tags:

c#

While reviewing a PR today I saw this in a class:

public bool ?Selected { get; set; }   //question mark in front of property name

I suspected that the developer meant this

public bool? Selected { get; set; }  //question mark at end of type

I was surprised that this even complied so I tried it myself and found that this is legal code and it ends up doing the same thing.

My question is: Is there any subtle (or not so subtle) difference between these two?

like image 998
HitLikeAHammer Avatar asked Mar 20 '18 20:03

HitLikeAHammer


2 Answers

First of all, my Visual Studio 2017 immediately corrects this

public bool ?Selected { get; set; } 

To this

public bool? Selected { get; set; } 

Then, IL DASM to the rescue! You can see that the resulting IL is the same, just like @mjwills said in the comments:

enter image description here

enter image description here

In the end, you can always hit Ctrl+K + Ctrl+D to have Visual Studio reformat your code and properly manage blanks and indentation.

As per your question about changing bool? to bool, it depends: if something can have an indefinite value or state, just like checkboxes, you should use bool?; otherwise bool is fine.

like image 167
Francesco B. Avatar answered Nov 11 '22 13:11

Francesco B.


It might make a little more sense when you realize that the following is also valid:

public bool?Selected { get; set; } 

? in that context is the nullable type identifier and as such it can't be followed by any character that would make sense in the current token, so the lexer simply processes the nullable type identifier and starts lexing the following expected token. Whats really redundant is the whitespace, its more a format helper to make it more readable than a syntax requirement.

Whitespaces are in many contexts meaningless trivia the compiler could do without.

Its similar in a sense as to why the following are all valid:

static bool Huh<T >() { return false; }
static bool Huh<T > () { return false; }
static bool Huh <T > () { return false; }
etc.
like image 1
InBetween Avatar answered Nov 11 '22 14:11

InBetween