rspec/rules/S2955/csharp/rule.adoc

61 lines
1.2 KiB
Plaintext
Raw Normal View History

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 16:49:39 +02:00
== Noncompliant Code Example
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 16:49:39 +02:00
== Compliant Solution
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)
{
// ...
}
// ...
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]