Home > Back-end >  Read property in an anonymous object while creating the object. C#
Read property in an anonymous object while creating the object. C#

Time:07-18

Is there a way for me to read a property value I defined already in an anonymous object while creating the object?

here is an example

var a = new { PropA = "something", PropB = this.PropA   " and another thing"}

CodePudding user response:

Perhaps defining it in a variable right before the declaration of a would work?

var somethingValue = "something";

var a = new { PropA = somethingValue , PropB = somethingValue    " and another thing"}

Otherwise, I don't think you would be able to. You have yet to instantiate the object so this.PropA wouldn't work. To further elaborate, your question was "Is there a way for me to read a property value I defined already in an anonymous object while creating the object?" which doesn't entirely make sense, because you are creating the anonymous object, so the value isn't already defined in the object.

CodePudding user response:

Using dynamic binding can be helpful:

dynamic myObject = a;
myObject.PropB  = ... //you can access any property that you know it exists
  • Related