what is the difference between string? and string in c#?

85 views Asked by At

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?

4

There are 4 answers

0
Olivier Jacot-Descombes On BEST ANSWER

string? and string are the same type. This is true for all reference types and reference types only.

In a nullable context the ? is a hint telling that null is a valid value for this field, variable, parameter or return value. Omitting ? on the other hand means that a value of null is 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.

4
Thomas Koelle On

Many articles have been written about this, but the TLDR is that nullable types was not made until C# 2.0 and therefore it is all a result of history how all is interpreted now. For backward compatibility string without ? has to be nullable.

0
TheQuaX 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
Barreto 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.