I'm trying to use declaration patterns as described here: https://learn.microsoft.com/dotnet/csharp/language-reference/operators/patterns#declaration-and-type-patterns
I can see that the examples only mention using declaration patterns in if conditions, like this:
object greeting = "Hello, World!";
if (greeting is string message)
{
Console.WriteLine(message.ToLower()); // output: hello, world!
}
Patterns do generally work outside of if conditions, i.e. anywhere you could put a Boolean expression. So I could write this:
var isString = greeting is string;
But then if I try making it a declaration pattern, I get a compiler error... not from the declaration pattern itself, but only when I try using the declared variable:
var isString = greeting is string str;
Console.WriteLine(str); // Compiler Error CS0165: Use of unassigned local variable 'str'
Intuitively, I would expect the variable str to be initialized with the value of greeting just like when I do that in an if condition. Is there a way I can get it to work?
greetingis not astring? If you are sure it is, you can simply use a cast.if (isString) { }. If you want to post an answer explaining that this is the reason why it's impossible, I'd accept it. It's just weird that I'm allowed to declare the variable outside of an if condition in the first place.