I've done some research, but have not found an answer to this. Is there a to represent the null case in the c# 8 switch expressions in such a way that the compiler will recognize and not trigger a warning for the reference x
in the base case when calling ToString()
? It seems like this is an obvious case and that I should not need to use the null forgiving operator !
in this case.
public override int? ConvertToInt(object? value) => value switch
{
var x when x == null => null,
int x => x,
var x => int.Parse(x!.ToString())
};
I have a feeling that they just haven't got to this yet, but I figured I'd toss the question out there.
Edit:
I did come up with a way to eliminate the need for the null forgiving operator, but I'm still curious as to if there's a specific null case syntax that is recognized. This doesn't feel like the best way as it's not completely clear, and I'm not even sure if this will be honored as I don't think Nullable references actually affect anything at run time, I will test this shortly.
public override int? ConvertToInt(object? value) => value switch
{
int x => x,
// notice the non-nullable object
object x => int.Parse(x.ToString()),
_ => null
};
Edit 2:
It looks like I was mistaken, this does seem to be honored. When running the following test the assertion did not fail.
[TestMethod]
public void MyTestMethod()
{
object? could_be_null = null;
string? str = could_be_null switch
{
object x => x.ToString(),
_ => null
};
Assert.IsNull(str);
}