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:
I would like to implement the suggestion, but cannot figure out how. Any help would be appreciated, thanks.
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.
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.