-2

I'm trying to find a way to iterate through all the fields in any object.

Firstly I tried using projection to get the value fields and print them, this worked nicely:

 var ob = new {DeclarativeSecn = "da" , sksksk = "dingdong" };
       
 foreach (PropertyInfo property in ob.GetType().GetProperties())
      {
             Console.WriteLine(property.Name + " val " +  property.GetValue(ob));
       }

However of course, I want to set the fields to some new values, so after reading up on it, it looks like this should work:

 foreach (PropertyInfo property in ob.GetType().GetProperties())
      {
             property.SetValue(ob,"new String");
       }

This gives me "property set method not found". I also try giving null as an argument, which is done in some places:

 property.SetValue(ob,"new String",null);

This has the same results. Why does this fail on me?

EDIT: It has been pointed out to me that I have not sufficiently described my goal. As stated above the goal is to iterate through the fields in any object, just like this example object:

 var ob = new {DeclarativeSecn = "da" , sksksk = "dingdong" };

And then also in the original question, I write "I want to set the fields to some new values" this means that I would like to iterate through the fields in the "ob" object, and set them to a new value.

Thank you

0

2 Answers 2

1

Why does this fail on me?

For the same reason that writing

ob.DeclarativeSecn = "new value";

would fail at compile-time, at least for the example you've given. Your object is an anonymous type, and the properties on anonymous types only have getters - they don't allow you to set new values for the properties. If you want to be able to modify the properties afterwards, don't use anonymous types.

Note that your question talked about iterating over the properties of any object, but:

  • When printing, you're assuming that all the properties have getters; that's commonly true, but not always
  • When setting new values, you're assuming that all the properties have getters and that they're string properties

Neither of those assumptions is correct in general. So if you want to be able to handle any object, you'll need to add rather more checking.

2
  • yes thank you, do you know of any good way to create objects that are not anonymous inline? such that I don't have to go about making a new class just for at simple test?
    – n00bster
    Dec 13, 2020 at 15:34
  • @n00bster: For what you've shown, you could just use a Dictionary<string, object> instead. We don't really know what bigger purpose you're trying to achieve.
    – Jon Skeet
    Dec 13, 2020 at 16:03
0

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.

Emphasis mine.

It seems you can't set a value on a read-only property. Sounds reasonable.

Not the answer you're looking for? Browse other questions tagged or ask your own question.