Search code examples
c#asp.netc#-4.0anonymous

C# Conditional Anonymous Object Members in Object initialization


I building the following anonymous object:

var obj = new {
    Country = countryVal,
    City = cityVal,
    Keyword = key,
    Page = page
};

I want to include members in object only if its value is present.

For example if cityVal is null, I don't want to add City in object initialization

var obj = new {
    Country = countryVal,
    City = cityVal,  //ignore this if cityVal is null 
    Keyword = key,
    Page = page
};

Is this possible in C#?


Solution

  • Its not even posibble with codedom or reflection, So you can end up doing if-else if you really need this

    if (string.IsNullOrEmpty(cityVal)) {
        var obj = new {
            Country = countryVal,
            Keyword = key,
            Page = page
        };
    
        // do something
        return obj;
    } else {
        var obj = new {
            Country = countryVal,
            City = cityVal,
            Keyword = key,
            Page = page
        };
    
        //do something 
        return obj;
    }