Digital Powers
Digital Powers

Reputation: 470

Accessing a member of an anonymous type during construction

Is there any way to access a member of an anonymous type during its construction?

For example

 enumerable.select(i => new
 {
     a = CalculateValue(i.something), // <--Expensive Call
     b = a + 5 // <-- This doesn't work but i wish it did
 }

Willing to consider alternatives to achieve the same goal, which is basically that I am projecting my enumeration and part of the projection is an expensive calculation, the value of which gets used multiple times, I don't want to repeat it, also repeating that call just doesn't feel DRY.

Upvotes: 4

Views: 82

Answers (1)

horgh
horgh

Reputation: 18534

That is not possible as the new anonymous object has not yet been actually assigned, and consequently its properties are not available either. You may do the following:

enumerable.select(i =>
    {
        //use a temporary variable to store the calculated value
        var temp = CalculateValue(i.something); 
        //use it to create the target object
        return new 
        {
            a = temp,
            b = temp + 5
        };
    });

Upvotes: 6

Related Questions