Is there a terse way to write the same in C#, say using null conditional or null coalescing operator? I seem to be missing something here with the null conditional operator usage.
//var hopefullySomeBool = (bool)someClassVariable.ChildClassProperty?.SomeStringProperty.Contains("Blah");
internal class SomeClass
{
public SomeChildClass ChildClassProperty { get; set; }
}
internal class SomeChildClass
{
public string SomeStringProperty { get; set; }
}
internal class Program
{
static void Main(string[] args)
{
SomeClass someClassVariable = new SomeClass();
if ( someClassVariable.ChildClassProperty != null
&& someClassVariable.ChildClassProperty.SomeStringProperty != null
&& someClassVariable.ChildClassProperty.SomeStringProperty.Contains("Blah")
)
{
Console.WriteLine("found Blah");
}
Console.WriteLine("Blah not found");
}
}
Maybe this?
var result = someClassVariable.ChildClassProperty?.SomeStringProperty?.Contains("Blah") == true ?
"found Blah" :
"Blah not found";
Console.WriteLine(result);