-3

I have two objects that are both type Shoppingcart. One is called shoppingcartA, the other shoppingcartDefault.

shoppingcartA has some of the properties set, but some are NULL. I want to replace every property of shoppingcartA that is NULL with the value that shoppingcartDefault has.

The problem is that I don't know the names of these properties (or I do, but there are 100 properties and I don't want to manualy type them all).

I've looked at a foreach that loops over every property that shopingcartA has but couldn't find a way to then take that same property from shoppingcartDefault and stick it in there.

Parrotmaster
  • 647
  • 1
  • 7
  • 27
  • Have you tried reflection: e.g.: `typeof(ShoppingChart).GetProperties(...)`? – Stefan Sep 07 '20 at 16:44
  • 1
    @Stefan I have. Managed to get it working (although for int's apparently they need to be nullable since they default to 0). If you add it as an answer I can accept it. – Parrotmaster Sep 07 '20 at 17:22
  • 1
    You can do it with reflection but you probably shouldn't. If the object has so many properties you can't copy them manually then it's likely a poor design and you should refactor. Instead of an object with hundreds of properties it sounds like your shopping cart should be a collection. – MikeJ Sep 07 '20 at 18:07

1 Answers1

1

You can map like this

foreach (var propertyInfo in test2.GetType().GetProperties())
        {
            if (propertyInfo.GetValue(test2) == null)
            {
                propertyInfo.SetValue(test2, propertyInfo.GetValue(test1));
            }

        }
Mustafa Arslan
  • 774
  • 5
  • 13