I'm new to C#, I've seen some people write string? SomeVar;
in YouTube. I just want to know what is the use of the ?
symbol.
I've tried to Google it but I didn't get anything I wanted.
I'm new to C#, I've seen some people write string? SomeVar;
in YouTube. I just want to know what is the use of the ?
symbol.
I've tried to Google it but I didn't get anything I wanted.
C# 8 has introduced a new feature called nullable reference types:
In a nullable oblivious context, all reference types were nullable. Nullable reference types refers to a group of features enabled in a nullable aware context that minimize the likelihood that your code causes the runtime to throw
System.NullReferenceException
. Nullable reference types includes three features that help you avoid these exceptions, including the ability to explicitly mark a reference type as nullable:
- Improved static flow analysis that determines if a variable may be null before dereferencing it.
- Attributes that annotate APIs so that the flow analysis determines null-state.
- Variable annotations that developers use to explicitly declare the intended null-state for a variable.
So string?
denotes a nullable string which allows compiler to emit appropriate warnings when developer does not perform appropriate checks to reduce NREs.
Note that there is another similar feature - nullable value types which is a bit different (which worth a separate discussion =).
Read more:
?
means that the field\property can be null. string?
is a nullable string,
int?
is a nullable int and so on.