NSubstitute icon indicating copy to clipboard operation
NSubstitute copied to clipboard

ReturnsNull doesn't work with nullable reference types

Open rcdailey opened this issue 3 years ago • 1 comments

Describe the bug I get compiler error:

The type 'bool?' must be a reference type in order to use it as parameter 'T' in the generic type or method 'ReturnsExtensions.ReturnsNull<T>(T)'

If I use ReturnsNull() extension method with a property declared as public bool? IsEnabled {get;}

To Reproduce See example code above.

Expected behaviour I should be able to use this extension method with value types wrapped with nullable.

Environment:

  • NSubstitute version: 4.3.0
  • NSubstitute.Analyzers version: 1.0.15
  • Platform: dotnet6

rcdailey avatar Feb 19 '22 19:02 rcdailey

Probably a matter of Taste. The developer put a class constraint on these extensions.

So you cannot use them for nullable structs.

Sadly a C# restriction. There is no way of telling the compiler that you only want types assignable to null.

You could remove the reference type constraint and work with default(T) instead. Then your case would work.

But this would open the extension method for every type. So when you change this, you can also write ReturnsNull for plain integers, which would return 0. Some may argue so what, but for many developers it is already hard to understand what NSubstitute does behind the scenes.

Another option would be to catch these at runtime and via the analyzers.

Ergamon avatar Feb 21 '22 13:02 Ergamon

As this is by-desgin I won't tag this as bug. But maybe we could improve this case in the future

304NotModified avatar Apr 29 '24 12:04 304NotModified