2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
When constraints have not been applied to restrict a generic type parameter to be a reference type, then a value type, such as a ``++struct++``, could also be passed. In such cases, comparing the type parameter to ``++null++`` would always be false, because a ``++struct++`` can be empty, but never ``++null++``. If a value type is truly what's expected, then the comparison should use ``++default()++``. If it's not, then constraints should be added so that no value type can be passed.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
private bool IsDefault<T>(T value)
{
if (value == null) // Noncompliant
{
// ...
}
// ...
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
private bool IsDefault<T>(T value)
{
if(object.Equals(value, default(T)))
{
// ...
}
// ...
}
----
or
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
private bool IsDefault<T>(T value) where T : class
{
if (value == null)
{
// ...
}
// ...
}
----
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Use a comparison to "default(xxx)" instead or add a constraint to "xxx" so that it can't be a value type.
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== on 22 May 2015, 10:04:25 Tamas Vajk wrote:
Fixed some minor wording issues, and the sample
=== on 22 May 2015, 12:07:32 Ann Campbell wrote:
Thanks [~tamas.vajk]. Looks good.
=== on 29 May 2015, 12:50:40 Tamas Vajk wrote:
\[~ann.campbell.2] Could you run through the description? I've change the wording "false negative" because it sounded strange.
=== on 29 May 2015, 14:50:44 Ann Campbell wrote:
looks good [~tamas.vajk]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]