References types are nullable by default and it is possible to assign a null value to string. What is the point of string? then? What difference does it make in this case?
what is the difference between string? and string in c#?
85 views Asked by Efe Belli At
4
There are 4 answers
0
On
If you are using C# 8.0 or later with nullable reference types enabled, a string variable is expected to never be null and the compiler will issue warnings if it might be set to null.
string nonNullableString = null; //Compiler warning with nullable reference types enabled
string? nullableString = null; //No compiler warning
0
On
Functionality is the same but for example when you assign a null value to string you might get a CS8600 warning while with string? you won't because you explicitly declared a nullable field.
string?andstringare the same type. This is true for all reference types and reference types only.In a nullable context the
?is a hint telling thatnullis a valid value for this field, variable, parameter or return value. Omitting?on the other hand means that a value ofnullis not expected. It allows the compiler to do a static analysis of your code and to issue a warning when it could result in a null-reference-exception. It also allows you to avoid unnecessary null-checks.