rspec/rules/S2955/csharp/rule.adoc

63 lines
1.9 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
In C#, without constraints on a generic type parameter, both https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types[reference] and https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types[value] types can be passed. However, comparing this type parameter to `null` can be misleading as value types, like `struct`, can never be null.
2021-04-28 16:49:39 +02:00
== How to fix it
To avoid unexpected comparisons:
2021-04-28 16:49:39 +02:00
* if you expect a value type, use https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default#default-operator[default()] for comparison
* if you expect a reference type, add a https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters[constraint] to prevent value types from being passed
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
bool IsDefault<T>(T value)
2021-04-28 16:49:39 +02:00
{
if (value == null) // Noncompliant
{
// ...
}
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
bool IsDefault<T>(T value)
2021-04-28 16:49:39 +02:00
{
if (EqualityComparer<T>.Default.Equals(value, default(T)))
2021-04-28 16:49:39 +02:00
{
// ...
}
}
----
2021-04-28 16:49:39 +02:00
or
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
bool IsDefault<T>(T value) where T : class
2021-04-28 16:49:39 +02:00
{
if (value == null)
2021-04-28 16:49:39 +02:00
{
// ...
}
}
----
== Resources
=== Documentation
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters[Constraints on type parameters]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types[Reference types]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types[Value types]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default#default-operator[`default` operator]
include::../rspecator.adoc[]