2023-05-03 11:06:20 +02:00
|
|
|
== Why is this an issue?
|
|
|
|
|
2021-04-28 16:49:39 +02:00
|
|
|
In the interests of keeping code clean, the simplest possible conditional syntax should be used. That means
|
|
|
|
|
|
|
|
* using the ``++??=++`` operator for a self-assign-if-not-null operation,
|
|
|
|
* using the ``++??++`` operator for an assign-if-not-null operation, and
|
|
|
|
* using the ternary operator ``++?:++`` for assignment to a single variable.
|
|
|
|
|
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
|
|
|
----
|
|
|
|
object a = null, b = null, x;
|
|
|
|
|
|
|
|
if (a != null) // Noncompliant; needlessly verbose
|
|
|
|
{
|
|
|
|
x = a;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
x = b;
|
|
|
|
}
|
|
|
|
|
|
|
|
x = a != null ? a : b; // Noncompliant; better but could still be simplified
|
|
|
|
|
|
|
|
x = (a == null) ? new object() : a; // Noncompliant
|
|
|
|
|
|
|
|
if (condition) // Noncompliant
|
|
|
|
{
|
|
|
|
x = a;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
x = b;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (a == null) // Noncompliant
|
|
|
|
a = new object();
|
|
|
|
|
|
|
|
var y = null ?? new object(); // Noncompliant
|
|
|
|
|
|
|
|
a = a ?? new object(); // Noncompliant for C# 8
|
|
|
|
----
|
|
|
|
|
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
|
|
|
----
|
|
|
|
object x;
|
|
|
|
|
|
|
|
x = a ?? b;
|
|
|
|
x = a ?? b;
|
|
|
|
x = a ?? new object();
|
|
|
|
x = condition ? a : b;
|
|
|
|
a ??= new object();
|
|
|
|
var y = new object();
|
|
|
|
a ??= new object();
|
|
|
|
----
|
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 the "[?:|??|??=]" operator here.
|
|
|
|
|
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 8 Jul 2015, 08:39:56 Tamas Vajk wrote:
|
|
|
|
\[~ann.campbell.2] LGTM
|
|
|
|
|
|
|
|
=== on 11 Dec 2015, 08:51:07 Tamas Vajk wrote:
|
|
|
|
\[~ann.campbell.2] I reformatted the description (uses a list now), and added the missing code samples.
|
|
|
|
|
|
|
|
=== on 11 Dec 2015, 13:56:45 Ann Campbell wrote:
|
|
|
|
looks good
|
|
|
|
|
2021-06-03 09:05:38 +02:00
|
|
|
endif::env-github,rspecator-view[]
|