Home > database >  How to check if non-nullable object is not null?
How to check if non-nullable object is not null?

Time:07-18

I need to write validation method that validates if non-nullable/nullable object is valid.

For example:

public void Example()
{
    object obj = null; //Can't be null.
    object? obj2 = null; //Can be null.
    object obj3 = new(); //Can't be null.
    object? obj4 = new(); //Can be null.

    var objIsValid = ObjIsValid(obj); //false
    var obj2IsValid = ObjIsValid(obj2); //true
    var obj3IsValid = ObjIsValid(obj3); //true
    var obj4IsValid = ObjIsValid(obj4); //true
}

How to make method like this?

public bool ObjIsValid(object obj)
{
     if(!obj.MarkedWithQuestionMark(obj) && obj is null) 
          return false;
     return true;
}

CodePudding user response:

You simply write it is such:

public bool ObjIsValid(object obj) => obj is not null;

In other words, I wouldn't consider whether the original type was nullable or not at all. Nullalbe Reference Types are a feature for static analysis. During runtime there is nothing preventing a variable that was not defined as a nullable reference to contain a null (also see this Q&A).

It is just not worth the effort to check if something could be null and only check it then. Simply check it, and be done with it.

Besides, even if you really wanted to write a MarkedWithQuestionMark(object obj) function, the point is you can't. There is no way to check if a variable was annotated as a nullable reference type. This information is only available during compile time. There is no meta information left in the IL that can help here.

  • Related