string? vs string in C#

Shervan360 1,681 Reputation points
2023-07-23T08:52:32.4266667+00:00

Hello,

As you know, string can return null.

What is the difference between string? vs string in C#?

namespace ConsoleApp1
{
     internal class Program
     {
          static string? ReturnStringNull()
          {
               return null;
          }
          static string ReturnString()
          {
               return null;
          }
          static void Main(string[] args)
          {
               ReturnStringNull();
               ReturnString();
          }
     }
}

Screenshot 2023-07-23 015014

Developer technologies | .NET | Other
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Hui Liu-MSFT 48,706 Reputation points Microsoft External Staff
    2023-07-24T07:31:34.85+00:00

    Hi,@Shervan360 . Welcome Microsoft Q&A.

    In C#, string? and string are different in terms of nullable reference types.

    string?:

    This represents a nullable string, which is a string that can have a value or be null.

    The ? after the type indicates that the variable can be assigned a value of the specified type or be assigned null.

    In C# 8.0 and later versions, nullable reference types are enabled by default, so string? is treated as a nullable string. It means the compiler will perform static analysis to help prevent null reference exceptions.

    string:

    This represents a regular non-nullable string, which cannot be assigned a value of null.

    Without the ?, the string variable is treated as a regular string, and it must always have a valid string value.

    The behavior of nullable reference types might vary depending on the version of C# and the compiler settings. Starting from C# 8.0 (Nullable reference types in C#), nullable reference types are enabled by default, but you can also control their behavior with the use of nullable annotations and nullable context options.


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    7 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.