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?
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With