Block-scoped type narrowing with the is
operator
#9136
-
I'm not sure how to call this, or if this has been requested before, so I'm not marking it as a proposal yet. object greeting = "Hello, World!";
if (greeting is string message)
{
Console.WriteLine(message.ToLower()); // output: hello, world!
} I should be able to just write this, since the compiler can already narrow the type of object greeting = "Hello, World!";
if (greeting is string)
{
Console.WriteLine(greeting.ToLower()); // output: hello, world!
} Similarly, this should work: object greeting = "Hello, World!";
if (greeting is not string) return;
Console.WriteLine(message.ToLower()); // output: hello, world! The compiler already does something similar when it applies nullability constraints, so this doesn't seem like a far-fetched idea, and it fits into the language nicely, no new keyword or alien syntax would be necessary. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 16 replies
-
While this isn't strictly about generics, this looks like it would be similarly solved by generic bridges (#6308). [Edit] Or maybe not, since you're checking the instance type rather than a static type. |
Beta Was this translation helpful? Give feedback.
-
Unfortunately this would break existing code as if the type of the variable changes within a scope then all method resolution within that scope is impacted. |
Beta Was this translation helpful? Give feedback.
-
There are ways to work around breaking existing code. For example:
This thread seems related to #6308... there you'll see examples like: public static bool TryParse<T>(this string? s, IFormatProvider? provider, out T? value)
{
// New code: Shortcut if T is IParseable<T> (now illegal because T is a type, not an instance):
if (T is IParseable<T> TParseable) // TParseable is a constrained type argument now
return TParseable.TryParse(s, provider, out value);
// Original code: trying to use TypeConverters as fallback etc...
} |
Beta Was this translation helpful? Give feedback.
Unfortunately this would break existing code as if the type of the variable changes within a scope then all method resolution within that scope is impacted.