Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

315
Views
How to resolve 'Use not null pattern...' suggestion in switch statement

In Visual Studio 2019, trying to use some newer features of c#, specifically newer features of the switch statement.

I want to switch on the type of an object, and I've seen a few ways to accomplish this, I'm using this approach:

private string MyFunc (Employee q)
  ....
  Type qt = q.GetType();
  switch (qt)
  {
     case Type _ when qt == typeof(HumanResources):
         //some code
         break;
     case Type _ when qt == typeof(Sales):
         //some code
         break;
     .....
     default:
         break;
  };
  .....
}

I've changed class names and obviously am not showing all code. However the case Type has the squiggly lines with the following suggestion/comment:

enter image description here

I would like to implement the suggestion, but cannot figure out how. Any help would be appreciated, thanks.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I do not experience that warning/error/suggestion in VS2022.

That said, I'd like to suggest you instead use the switch statement more properly:

private string MyFunc(Employee q)
{
    switch (q)
    {
        case HumanResources:
            //some code
            break;
        case Sales:
            //some code
            break;
         default:
            break;
    };
    return null;
}

So instead of operating against the Type metadata, you are operating against the instances themselves. This dispenses with any need for the when operator and the code appears much more readable to me.

over 4 years ago · Santiago Trujillo Report

0

Don't switch on the variable's type, switch on the variable itself and use pattern matching to select the right case based on the type.

private string MyFunc (Employee q)
{
    switch (q)
    {
        case HumanResources hr:
            // some code
            break;
        case Sales s:
            // some code
            break;
        // ...
    }

    // ...
}

You don't need to add a variable name (hr, s) in the case, it's there in case you need to access the variable as that particular type.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!