0

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"}

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

yes that would work but in my case it would involve creating a nice few variables and I'm looking for a shorter and cleaner way, thanks anyway
You'll have the variable information stored somewhere anyways, right? It may be cleaner to have that value stored in one place that is then the reference for multiple other variables, rather than having a chain of variables you would need to traverse through in order to see what the actual intent was. Totally depends on use case though.
I'm creating this object in a LINQ select statement and I HATE having huge select statements, I like when they are just one line... I guess I'll just have to create these vars...
I agree, the huge selects can be an eyesore. It ultimately will depend on your use case. We don't know the full context of your situation, perhaps there's an even better solution if it were to be approached from a different angle.
0

Using dynamic binding can be helpful:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.