Proposal: Add "block expressions" #9673
-
Currently, when we need to assign a value from a sequence of operations to a variable, we have to create a dummy variable to hold the current result of the operation before continuing to the next operations. Take a look at this example: A a = new A();
a.Something();
a.SomethingElse();
B b = new B();
b.SomethingWith<A>(a);
b.Freeze();
C c = new C {
B = b
}; The code above is already readable, although the dummy variables will clutter the current scope and preventing us to create another variable with the same name even if the variable is unused later. We can still prevent the scope cluttering with the help of a new block (scope), like this: C c;
{
A a = new A();
a.Something();
a.SomethingElse();
B b = new B();
b.SomethingWith<A>(a);
b.Freeze();
c = new C {
B = b
};
} The code above is also readable and avoid scope cluttering, but it looks inconsistent (in term of writing style) with the surrounding code. In this proposal, I'm proposing to add "block expressions" to C# which will make the code stay consistent, concise, and easy to read. So, the code looks like this: C c = new C {
B = block: {
A a = new A();
a.Something();
a.SomethingElse();
B b = new B();
b.SomethingWith<A>(a);
b.Freeze();
break :block b;
};
} This idea is inspired by Zig, feel free to make some modifications to this proposal if needed. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Beta Was this translation helpful? Give feedback.
Dupe of #3086 / #9242.