Target-typed casting #7017
Replies: 6 comments 23 replies
-
Everything you asked already works IReadOnlyList<int> list1 = collection;
var list2 = (IReadOnlyList<int>)collection;
IReadOnlyList<int> list3 = (IReadOnlyList<int>)collection; |
Beta Was this translation helpful? Give feedback.
-
@FaustVX what I'm suggesting here is a new syntax for those casting cases (assuming |
Beta Was this translation helpful? Give feedback.
-
This would be similar to how |
Beta Was this translation helpful? Give feedback.
-
The gist of the request, the way I understand it, is that you want The problem is that in those types of expressions the Also, even if we were to find a different symbol other than |
Beta Was this translation helpful? Give feedback.
-
These criteria are already satisfied by the The only thing I could think of was that var list = collection.(IReadOnlyList<int>); |
Beta Was this translation helpful? Give feedback.
-
Why do you want to be able to write |
Beta Was this translation helpful? Give feedback.
-
target-typed new expressions are a great way to improve code readability. A similar idea could be applied when declaring a variable and assigning it from the result of an explicit cast.
For instance, instead of:
var list = (IReadOnlyList<int>)collection;
or
IReadOnlyList<int> list = (IReadOnlyList<int>)collection;
we could write
IReadOnlyList<int> list = collection!;
The bang operator is just used to provide a syntax example and a different syntax could be used as long as
ed: adding more details following the comments below:
To me target-typed new expressions have been created to improve readability of variable declaration and assignment on the same line and avoid having to duplicate the type.
Before them, we could write:
Class c = new Class()
and
var c = new Class()
In the first case, it's obvious that
c
is aClass
since the type precedes the name of the variable, but the type is duplicated.In the second it is not duplicated but it's a little bit less obvious to know what
c
is.Target-typed new expressions allow the best of both worlds:
Class c = new()
My suggestion is to add a similar feature to other declaration + assignment cases, in particular when declaring a variable and assigning it to the result of an explicit cast.
Beta Was this translation helpful? Give feedback.
All reactions