Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a terse way to write this conditional expression in C#

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading