简体   繁体   中英

Non-Nullable becomes Nullable on return

I think I've seen this question answered somewhere, but I can't find it and don't remember the answer.

Assuming Nullable-Reference-Types is enabled.

There is a method that returns a string . The caller of the method stores the resulting string into a variable. The variable will be Nullable, even if the method's return value is non-nullable.

static string MyMethod() 
{
   return "Hello World!";
}

public static void Main() 
{
   // result is of type string? here. Hence nullable.
   var result = MyMethod();

   // result2 is also nullable here.
   string result2 = MyMethod();
}

The same does not seem to happen with primitive types, but it does happen reference types, like object . Kind of defeats the purpose of NRT for me. I'm sure there's a reason for this and it's "by design".

在 C# 8.0 中,字符串被称为可以为空的“字符串!”,因此 Allow Null 注释允许将其设置为 null,即使我们返回的字符串不是 null(例如,我们进行比较检查并将其设置为如果为 null,则为默认值。)

"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM