string? vs string in C#

Shervan360 1,601 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

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,919 questions
C#
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.
11,010 questions
{count} votes

Accepted answer
  1. Hui Liu-MSFT 48,571 Reputation points Microsoft Vendor
    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.

    4 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

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