Search code examples
c#stringnullnullable-reference-types

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


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?


Solution

  • 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.