سؤال

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

هل كانت مفيدة؟

المحلول

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;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top