Diagnostic for argument constraint with non-nullable type instead of nullable type
See original GitHub issueSplit from #1005. Inspired by #660.
Assuming you have this interface:
public interface IFoo
{
int Bar(int? x);
}
And a call configuration like this:
A.CallTo(() => foo.Bar(A<int>._)).Returns(42);
It’s easy to miss the fact that the constraint won’t match when the argument is null
(it used to throw a NRE, which at least indicated something was wrong, but now it silently rejects the null argument). It’s especially confusing because when you write A<int>._
, you usually mean “match anything”. The analyzer could detect this and emit a warning.
(I wish we could omit the type and just say A.CallTo(() => foo.Bar(A._)
, which is more concise and easier to get right. Java’s type inference is a little better in that regard. This syntax could also be achieved if we had a “bottom type” in C#.)
Issue Analytics
- State:
- Created 6 years ago
- Comments:9 (9 by maintainers)
Top Results From Across the Web
Constraints on type parameters - C# Programming Guide
The type argument must be a reference type, either nullable or non-nullable. This constraint applies also to any class, interface, delegate, ...
Read more >The type 'string' must be a non-nullable type in order to use ...
The Nullable<T> type requires that T is a non-nullable value type, for example int or DateTime . Reference types like string can already...
Read more >Regression with Nullable<T> and a generic type constraint ...
As a workaround you can write Nullable<TResult> in the override declaration.
Read more >C# 8 non-nullable references and the Try pattern
The challenge you'll face is that when using nullable reference types (NRT), the compiler will treat Foo<T> as non-nullable. But try and change ......
Read more >Improving non-nullable reference types handling
The main thing that started getting on my nerves was diagnostic CS8618: Non-nullable field is uninitialized. Consider declaring as nullable.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
The thing is, this analyzer is bound to cause false positives, because you can intentionally write
A<int>._
where aint?
is expected. This is why I want to provide a code-fix to easily change it to something that is equivalent and more obviously correct. But since I can’t do that forA<T>.That...
, the user would have to suppress the warning if it was intentional.So I think I’ll just restrict the warning to
Ignored
and_
.This change has been released as part of FakeItEasy 4.0.0.