-3

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#?

Knitschi
  • 2,822
  • 3
  • 32
  • 51

1 Answers1

2

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

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Blueberry
  • 2,211
  • 3
  • 19
  • 33