19

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

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Tepu
  • 1,602
  • 2
  • 20
  • 28
  • 1
    What would that even mean? The object would be missing a property that the rest of your code expects. What would `obj.City` mean? Semantically undefined. – usr Jun 07 '13 at 13:38
  • 1
    In my case I need to create an object which gets serialized into JSON (and send it using RestSharp) - no other manipulation of the object in c#. Based on conditions some of the members should be there, some not. As it is a large object, using accepted answer requires a lot of code. So this question is reasonable. Using some kind of conditional initialization would spare coding – przno Apr 11 '17 at 10:43
  • Possible duplicate of [is it possible to have a conditional field in an anonymous type](https://stackoverflow.com/questions/3090218/is-it-possible-to-have-a-conditional-field-in-an-anonymous-type) – KyleMit Nov 30 '17 at 15:39

4 Answers4

11

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;
}
Jeppe
  • 1,830
  • 3
  • 24
  • 33
Tepu
  • 1,602
  • 2
  • 20
  • 28
  • This works and seems like the only method for an anonymous object. But I would be against it because it adds duplication and complexity. The better way is to adjust the rest of the codebase to handle/ignore null fields. – Suciu Eus Sep 07 '21 at 12:08
5

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
            };
Serge
  • 6,554
  • 5
  • 30
  • 56
5

Well you would have if else conditions. But, if you are serilizing this as a JSON object with newtonsoft JSON this could help:

   var json = JsonConvert.SerializeObject(value, Formatting.None,
                    new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    });
gbubemi smith
  • 135
  • 4
  • 10
0

You could use an ExpandoObject and a functional extension method.

    pubic class SomeClass

        public dynamic DomainFunction(
            object countryVal = null
          , object cityVal = null
          , object key = null
          , object page = null
        )
        {
            dynamic obj = new ExpandoObject();

            cityVal?.Tee(x => obj.City = x);
            countryVal?.Tee(x => obj.Country = x);
            key?.Tee(x => obj.Keyword = x);
            page?.Tee(x => obj.Page = x);

            return obj;
        }

    }

    public static class FunctionalExtensionMethods{

        public static T Tee<T>(this T source, Action<T> action)
        {
          if (action == null)
            throw new ArgumentNullException(nameof (action));
          action(source);
          return source;
        }

    }