Allow object initializers to access previously initialized values #8785
Replies: 6 comments
-
Should this be allowed? new Foo { A = .A+.B };
|
Beta Was this translation helpful? Give feedback.
-
Though that code smells and it is not what I had in mind, I think it should be allowed. If either |
Beta Was this translation helpful? Give feedback.
-
That's right, it smells but it was a possibility I thought it's worth mentioning. I like your proposal by the way. |
Beta Was this translation helpful? Give feedback.
-
If Another thing to consider is that this would mean property getters and setters can both be used. If so, is there then any reason to prevent methods from being called? For example:
|
Beta Was this translation helpful? Give feedback.
-
@thargol1 Declaration expressions are already championed (#973) and would help somewhat: public static class Factory()
{
public static DummyDTO CreateDummyDTO() =>
new DummyDTO
{
A = var a = ExpensiveFunction(),
B = var b = AnotherExpensiveFunction(),
C = a + b
};
} Along this line, similar ask: #400 |
Beta Was this translation helpful? Give feedback.
-
@jnm2 I agree declaration expressions would help and it has a much wider use than object initializers. But the proposed syntax does not help the readability of the code. Or may be I just have to get used to it. @SilentSin I think you make a valid point and I agree it should be possible. B.t.w the dot-syntax is borrowed from the VB object initializers. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Allow object initializers to access previously initialized values
Consider this example:
Currently this does not compile. This example can be difficult to implement in the compiler, because the right hand A and B could also refer to properties or fields of the
Factory
object.But with a slight change of syntax, I think it can be implemented:
This could compile to:
Currently I use:
It works fine, but it is not as elegant as it could be and cannot be used in expressions.
I like the elegance of enums:
Beta Was this translation helpful? Give feedback.
All reactions