Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the is operator with unconstrained generics

C# Version: 7.2

My Ms Build version: Unknown (if anyone can tell me how to find it on my machine please do)

My Version of Visual Studio: Visual Studio Professional 2019

I'm going to boil this down to the bare minimum so disregard the simplicity of the code.

public bool IsNull<T>(T thing)
{
    return thing is null;
}

In Visual studio 2019 this is fine and it compiles.

I can call it like this

IsNull(0); //thats an int

and it compiles and returns false since ints are never null. I am happy and all is well.

However my build server is not happy. It is using MSBuild v15.5.180.51428 and it throws a compiler error saying

error CS0403: Cannot convert null to type parameter 'TValue' because it could be a non-nullable value type. Consider using 'default(TValue)'

This also happens on a colleagues machine using VS2017

Has this 'fix/change' been documented. What version of MSBuild is it available in?

Thanks

like image 985
Dave Avatar asked Jan 26 '23 07:01

Dave


2 Answers

This is indeed a bug. The pattern used there is a C# 8.0 pattern and should not compile when the language version is set to 7.2. This has already been reported and fixed in our code base though. It will be available in the MSBuild that comes with VS2019 Update 2.

  • https://github.com/dotnet/roslyn/issues/34678
like image 57
JaredPar Avatar answered Jan 28 '23 20:01

JaredPar


EDIT: This is a compiler bug in VS 2019 - this feature is in C# 8 only and from VS 2019 Update 1 on you need to enable C# 8 to get rid of this message.

This is a change that has been made in the compiler - you need at least Visual Studio 2019 tools (MSBuild 16) to build this code.

This was implemented in this PR for VS 2019: recursive-patterns(18): Permit a constant pattern to be used with an open type as input (though I was under the impression that C# 8 would need to be enabled for this but apparently not).

like image 20
Martin Ullrich Avatar answered Jan 28 '23 22:01

Martin Ullrich