mercredi 22 mars 2023

Why is variable declared with "declaration pattern" only available in if statement

For reference in this example I have this Person type, although it could be any type:

public class Person
{
   public Person? Partner { get; set; }
   public Person? Child { get; set; }
}

Somewhere else I am checking if the person has a partner and children, but its not required to declare either.

Currently it looks like:

Person partner = null!;
if (person.Partner is not null)
{
   partner = person.Partner;
   //do stuff
}

if (person.Child is Person child)
{
   if (partner is not null)
   {
      //do one way
   }
   else
   {
      //do other way
   }
   //do stuff
}

Live example

I wanted it to look something along the lines:

if (person.Partner is Person partner)
{
   //do stuff
}

if (person.Child is Person child)
{
   if (partner is not null)
   {
      //use partner
   }
   //other stuff
}

Live Example

partner on the last example is declared outside of the if statement scope, but is not assigned. How could I, using this pattern, let the compiler know that its either declared with the person.Partner reference or null!?

Much like the out keyword on the following example doesn't throw a "not declared" error:

SomeMethod(out Person partner);
if(partner is not null) { }

Live Example

I am learning about the C# patterns and have looked into the documentation and feature proposal and there is no mention of what I was looking for, not even why it is declared outside of the scope preventing me from using the variable name? Even if I tricked my way around the pattern using it on the needed scope as shown here its not declared.

Is the above first example the standard approach and only way to do it?

Aucun commentaire:

Enregistrer un commentaire