Search code examples
c#classintnon-nullable

Class declaration with switch gives warning that code is int in if statement always returns true, but false case of code also works


When using a custom class there is a switch that takes in an int. The switch then fills out the class where some cases have a num, and some do not. The int can range virtually anywhere in the application, but some cases do not have one. When the newClass is viewed the user needs to see what ones do not have a number. This code below works fine, except that there is an warning that needs to be removed for : "The result of comparing value type newClass.num with null is true" and "Unreachable code detected" for the false part of the statement.

Is there a method or best practice that can be used to test for nullReferenced parts of a class? What is this type of situation called(ie, non-nullable refencing, nullReference testing) (...because I don't know what to search for)?

using system.generic;
using system.generic.collections;

public Class newClass{
    string name;
    int num;
    public newClass(int index){
        switch(index){
            case 1:
                num = 20;
                name = "returns true";
                break;
            case 2:
                // no num here
                name = "returns false";
            default :
                break;
        }
    }
}
public otherClass{
    newClass foo = new newClass(1);
    newClass bar = new newClass(2);

    List<newClass> newClassList = new List<newClass>();
    newClassList.add(foo);
    newClassList.add(bar);

    foreach(newClass nc in newClassList){
        if(nc.num != null){
            print("True");
        } else {
            print("False");
        }
    }
}

Solution

  • the value is defined as an int which is a value type in C#, thus not nullable. You can remove your warnings by either making it an int?, i.e. a nullable integer. Or, in case 0 is not a possible value for num in your scenario, change your condition to be:

    // default(int) will be 0, the default value for a C# int
    if(nc.num != default(int)){
        print("True");
    } else {
        print("False");
    }