Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 544
Tepu Avatar asked Jun 07 '13 13:06

Tepu


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What do you mean by C?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C language w3schools?

C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

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;
}
like image 196
Tepu Avatar answered Oct 22 '22 22:10

Tepu


You can't do that.

But what you could do is provide the default value (null?) of those properties.

var obj=  new
            {
                Country= countryVal,
                City = condition ? cityVal : null,
                Keyword = condition ? key : null,
                Page = condition ? page : null
            };
like image 36
Serge Avatar answered Oct 22 '22 21:10

Serge