1

I have a simple line of code: lead.InternalCompany = nvCollection["ic"];

I want to set lead.InternalCompany to the value retrieved, but if nothing is there to a blank string ""

I've tried to use nvCollection["ic"].HasValue();

I know I could do something simple like this

string value = nvCollection["ic"];
if (value == null) // key doesn't exist
    {
        lead.InternalCompany = "";
    }

I'd ideally like a ternary if statement to accomplish this

Jon Harding
  • 4,928
  • 13
  • 51
  • 96
  • Its better to use `String.NullorEmpty(string)` instead of `value == null` – Shaharyar Aug 22 '13 at 14:56
  • @Shaharyar: That would depend on your implementation details. As far as we know, an empty string is a perfectly valid value. (and in Jon Harding's case, it's redundant as he wants to default to empty anyway) – Chris Sinclair Aug 22 '13 at 14:59

1 Answers1

8

Use the null-coalescing operator

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

lead.InternalCompany = nvCollection["ic"] ?? string.Empty;
Sam Leach
  • 12,746
  • 9
  • 45
  • 73