Home > OS >  Nullable value types & type safety with 'if not null checking' in c#. Does C# have 'T
Nullable value types & type safety with 'if not null checking' in c#. Does C# have 'T

Time:06-30

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)

CodePudding user response:

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)
  •  Tags:  
  • c#
  • Related