Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
Pattern matching in compound if statements and switches with fall-through

If I have an if statement like if (currentShape is ITable table || currentShape is AutoShape autoShape) I cannot use table or autoShape in the body because I get a CS0165 compiler error.

The same is true for a switch statement with fall-through:

void Foo(object o)
{
    switch (o)
    {
        case int i:
        case string s:
        case Guid g:
            string bar = i?.ToString() ?? s?.ToString() ?? g.ToString(); // cannot use i, s, or g.
            break;
    }
}

I understand why, but I'm left wondering, is this a limitation of pattern matching, i.e. you cannot use it in compound if statements, or is there a correct way to construct the statement so I can use either variable (e.g. by initializing them to null so I can then at least do a null check)?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Since C# 9 you can do the followings

with switch statement

switch (o)
{
    case object probe when probe is int or string or Guid:
        string bar = probe.ToString();
        break;
}    

and with switch expression

var bar = o switch
{
    int or string or Guid => o.ToString() 
};
over 4 years ago · Santiago Trujillo Relatório

0

If truly there are two separate things to achieve, don't combine the pattern expressions. Two separate if statements will work better.

if (currentShape is ITable table)
{
    // do something with tables
}

if (currentShape is AutoShape autoShape)
{
    // do something with autoshapes
}

However, your other example illustrates that perhaps there is some common functionality between the conditions. ToString() is probably a bad example, as you could just do:

string? bar = o.ToString(); // doesn't matter the type of object

But let's say that perhaps you want a different format applied depending on the type. In that case, a switch expression could be useful. For example:

string? bar =
    o switch
    {
        int i => i.ToString("D3"), // three digits
        Guid g => g.ToString("N"), // no hyphens
        string s => s,    // no need to call ToString on a string
        _ => o.ToString() // all other types
    };

You also asked about whether the variables could be initialized with nulls so you could do a null check. That wouldn't work for non-nullable types like int. For nullable types, it would cause an extraneous compare operations (first to test the type and assign null, second to test for null). Keeping the expressions separate ensures the minimal number of operations.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda