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");
}
}
>Solution :
Maybe this?
var result = someClassVariable
.ChildClassProperty?
.SomeStringProperty?
.Contains("Blah") == true
? "found Blah"
: "Blah not found";
Console.WriteLine(result);
Be aware that the null-conditional-operator returns Nullable<T>, so the left-hand side of your ==-operator is Nullable<bool>, not just bool. This is why you need to write Contains("Blah") == true instead of just using Contains("Blah").
Furthermore the ternary always returns something. You cannot use it in a void-returning expression such as Console.WriteLine. So this won’t compile:
mycondition ? Console.WriteLine("One") : Console.WriteLine("Two");