Home > database >  C# Null Conditional in Ternary condition
C# Null Conditional in Ternary condition

Time:10-27

Am refactoring some old code and see something in the following format:

Type = rec["IsFlagged"]?.ToString() == "True" ? "Yes" : "No"

which should not work if rec["IsFlagged"] is null, in which case I need to return null. How would one refactor to keep code in one line, if possible?

I can do something like but am wondering if the following can be achieved in one line to have minimal changes to code

    if (rec["IsFlagged"] != null)
    {
       return rec["IsFlagged"].ToString() == "True" ? "Yes" : "No"
    }
    else 
    {
        return null
    }

Thanks,

CodePudding user response:

The original code works fine.

rec["IsFlagged"]?.ToString() == "True" ? "Yes" : "No"

The ? operator before .ToString() prevents the method from being called if null. The result of rec["IsFlagged"]?.ToString() would be null

Then, it compares null to "True" which is false (they are not equal).

The ternary operator then evaluates "No" and assigns it to the lvalue.

EDIT So, now you want 3 possible results: "Yes", "No" or null. A single ternary only gives you two choices. There are many possibilities and yours is fine, unless you have multiple places doing something similar. In that case, you could use an extension method:

public String CheckTrue(this object input) {
    return input?.ToString() == "True" ? "Yes" : "No"
}

and then in your specific case:

return rec["IsFlagged"]?.CheckTrue()

Another alternative is to use multiple ternary operators?

return rec["IsFlagged"]==null ? null : (rec["IsFlagged"].ToString() == "True" ? "Yes" : "No");

CodePudding user response:

This will do want you want..

rec["IsFlagged"]?.ToString().Replace("True","Yes").Replace("False","No")

.. but you perhaps shouldn't want to do it!

I prefer Garr's suggestions, though if it's a bool inside rec (is rec a DataRow?) I'd skip the ToString/compare with string and just use it as a bool once we know it's not null

return rec["IsFlagged"]==null ? null : ((bool)rec["IsFlagged"] ? "Yes" : "No");

But all in I like the extension method approach more, and we can tweak it some, leveraging conversion between a bool-or-null-stored-in-object and bool?:

public static string ToNullaboolString(this bool? x, string t = "Yes", string f = "No", string n = null){
  if(x.HasValue) 
    return x.Value ? t: f;
  return n;
}

Calling it like:

((bool?)rec["IsXxx"]).ToNullaboolString()

or supplying parameters if you want to change the strings returned (localization?)

  • Related