简体   繁体   中英

Nullable value types & type safety with 'if not null checking' in c#. Does C# have 'Type promotion'?

In other languages (eg Dart), if you do an if (x != null) check then the x will be promoted to a non nullable type. Does c# have type promotion? What are the limitations in C#? eg if (x is Y) or in switch commands and other scenarios?

I have noticed nullable types are not promoted to non nullable types in C#. Is there any feature that can be turned on or this is this a limitation in the language?

public enum eColours { blue }

public class ColourClass {
  public eColours? call(string colour) {
    if (colour == "blue")
      return eColours.blue;

    return null;
  }

  public string describeColour(eColours colour) => colour.ToString();
}

var obj = new ColourClass();
var result = obj.call("blue");

if (result is not null) {
  var description1 = obj.describeColour(result); //error here
}

Edit

The particular solution I'm trying to solve has an && clause in the if expression? (Where colour & pet are both enums?)

if (colour != null && pet != null pet)

While the variables being tested aren't promoted themselves, you can expand your use of the is operator slightly to achieve what you're after:

if (result is eColours nonNullResult) {
  var description1 = obj.describeColour(nonNullResult);
}

This syntax combines both the type check and a cast to another variable if the type check is successful; the type of nonNullResult is specifically eColours , not eColours? , and you no longer get the conversion error.

In later versions of the language, you can also specifically check for not-null with this format:

if (result is { } nonNullResult)

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