[Proposal] Have 'is' operator type pattern assign value if right-hand variable already exists within scope #8814
Replies: 4 comments
-
This would essentially allow variable aliasing to happen through the back door - and the LDM have historically been very resistant to variable aliasing due to the number of subtle bugs it introduces. It's fairly regular that this comes up, but with a quick search I only found #1741; others may be able to provide references to other issues. |
Beta Was this translation helpful? Give feedback.
-
It seems that you forget the public bool ConvertChild<TDerived>(Container container, out TDerived child) where TDerived : Container
=> child = container as TDerived; |
Beta Was this translation helpful? Give feedback.
-
@huoyaoyuan That won't compile -- the method should return a |
Beta Was this translation helpful? Give feedback.
-
public bool ConvertChild<TDerived>(Container container, out TDerived child) where TDerived : Container
=> (child = container as TDerived) is object; not very pretty tho |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
For the entirety of this post, I will refer to the is operator in the context of the specific type pattern
item1 is T item2
.Currently, if an is operator's right-hand variable has the same name as one that already exists in the scope, a compiler error occurs. I believe it may simplify some code if a change were made:
true
, it castsitem1
as typeT
toitem2
.false
, it setsitem2
to the default for its type.This would allow you to shorten something like this:
To this:
However, I do see an issue with this. If is assigns something to an already-existing variable whether or not it fails, it practically becomes an assignment expression. Therefore, is may need to be considered a statement if this change is implemented.
Very importantly, because currently
item2
will be unassigned outside of whatever if statement the is operator is used in, any already existing code that usesitem2
outside of the if statement will have already have been required to assign a value to it before using it. Since all pre-existing code will already have assigned a value toitem2
before this change, giving it a default value outside the if statement won't affect anything, as it will have already been overridden. Therefore, this change shouldn't break any currently written code for anybody.Beta Was this translation helpful? Give feedback.
All reactions