Search code examples
c#nullreferenceexceptionnullable

Is there a way to return null instead of throwing a NullReferenceException?


I have the following C# problem.

Consider the function:

private String getStringFromNullabel()
{
    var nullable = getClass();  // returns some object that could be null
    if( nullable != null)
    {
         return nullable.Text;
    }
    return null;
}

This works but it is verbose and I would rather write something like:

private String getStringFromNullabel()
{
    return NotThrowWrapper(getClass()).Text; 
}

This will throw if getClass() returns null. So I am looking for some syntax that is short enough that this stays a one-liner but rather returns null instead of throwing an exception.

Is there such a thing in C#?


Solution

  • Pre C#6

    private String GetStringFromNullabel()
    {
     var nullable = getClass();  // returns some object that could be null
     return nullable  != null ? nullable .Text : null;
    }
    

    Post C# 6

    private String GetStringFromNullabel()
    {
     return getClass()?.Text;
    }
    

    Note that you should follow the .NET naming conventions