[Proposal] Support for type narrowing based on control flow analysis #9538
Unanswered
marco-carvalho
asked this question in
Language Ideas
Replies: 2 comments 2 replies
-
I'm a bit confused. Your null check and truthiness check examples already work in the language. |
Beta Was this translation helpful? Give feedback.
0 replies
-
The challenge with type narrowing case (like checking if an object is string) is that it will change the meaning of existing code. For example, causing overload resolution to change with code that uses that particular variable. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Add support for type narrowing where the compiler automatically refines variable types based on control flow analysis, similar to TypeScript's implementation.
Motivation
Currently, C# requires explicit casting or pattern matching even when the compiler could logically infer that a type has been narrowed through control flow. This leads to verbose code and unnecessary defensive programming.
Detailed Design
The compiler should narrow types in the following scenarios:
Null checks
Type checks with
is
Benefits
Alternatives
Related Work
This feature would significantly improve the ergonomics of working with nullable types and polymorphic code in C#.
Beta Was this translation helpful? Give feedback.
All reactions