Suggestion: Add syntactic sugar for IEnumerable property { get { yield return Something(); } } #3132
Replies: 10 comments
-
You can just add an extension for this: public static IEnumerable<T> ToEnumerable<T>(this T value)
{
yield return value;
}
// ...
public IEnumerable<string> MyProperty => GetSomething().ToEnumerable();
|
Beta Was this translation helpful? Give feedback.
-
Of course @CyrusNajmabadi, but that produces some minor issues:
Instead, if the compiler does that:
|
Beta Was this translation helpful? Give feedback.
-
This would be a breaking change if the return value of the method is both You can take it up with the Runtime repo to see if they are interested in adding |
Beta Was this translation helpful? Give feedback.
-
@HaloFour to avoid the breaking change couldn't be used the keyword |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
The compiler needing to add a full language feature to save form typign a single method call doesn't seem useful enough for such an extremely narrow case. How often are you yielding exactly one element? It's not common enough or difficult enough to warrant a language feature here. |
Beta Was this translation helpful? Give feedback.
-
@jnm2 it was mentioned in the OP. Or perhaps you mean the inferred-type version of the array? |
Beta Was this translation helpful? Give feedback.
-
Oh, well, so the complexity of the task is not worth. |
Beta Was this translation helpful? Give feedback.
-
Yes, the inferred-type version is next to no extra syntax. |
Beta Was this translation helpful? Give feedback.
-
Just a side note: public IEnumerable<string> MyProperty { get { yield return GetSomething(); } } and public IEnumerable<string> MyProperty => new string[] { GetSomething() }; are not equivalent. In the first case |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Just a humble idea:
Imagine that you want to make a property of
IEnumerable
, like this one:Everything is fine, but what if you only want to return a single element?
Like:
It's quite long.
You can reduce it as:
But then it makes a bit difficult to read.
Another thing you can do is:
But you are adding an array, which also increases noise, some readers may wonder why the array, and it's only executed when you call the property (not each time you use the IEnumerable).
Wouldn't be nice if you could just do?
And the compiler infers that and translate it to one of the examples above (which one is something that the development team should decide).
Maybe that could produce ambiguity in some obscure cases, like:
In order to prevent that the
yield
keyword could be used instead:Just an idea.
Beta Was this translation helpful? Give feedback.
All reactions