rspec/rules/S3257/csharp/rule.adoc

77 lines
2.3 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2023-10-16 11:06:00 +02:00
In C#, the type of a variable can often be inferred by the compiler. The use of the [var keyword](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables) allows you to avoid repeating the type name in a variable declaration and object instantiation because the declared type can often be inferred by the compiler.
2023-10-16 11:06:00 +02:00
Additionally, initializations providing the default value can also be omitted, helping to make the code more concise and readable.
2023-10-16 11:06:00 +02:00
Unnecessarily verbose declarations and initializations should be simplified. Specifically, the following should be omitted when they can be inferred:
* array element type
* array size
* ``++new DelegateType++``
* ``++new Nullable<Type>++``
* object or collection initializers ({})
* type of lambda expression parameters
* parameter declarations of anonymous methods when the parameters are not used.
2023-10-16 11:06:00 +02:00
== How to fix it
2023-10-16 11:06:00 +02:00
Remove any unneeded code. C# provides many features designed to help you write more concise code.
2023-10-16 11:06:00 +02:00
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
var l = new List<int>() {}; // Noncompliant, {} can be removed
var o = new object() {}; // Noncompliant, {} can be removed
var ints = new int[] {1, 2, 3}; // Noncompliant, int can be omitted
ints = new int[3] {1, 2, 3}; // Noncompliant, the size specification can be removed
int? i = new int?(5); // Noncompliant new int? could be omitted, it can be inferred from the declaration, and there's implicit conversion from T to T?
2023-10-16 11:06:00 +02:00
var j = new int?(5);
Func<int, int> f1 = (int i) => 1; //Noncompliant, can be simplified
class Class
{
private event EventHandler MyEvent;
public Class()
{
MyEvent += new EventHandler((a,b)=>{ }); // Noncompliant, needlessly verbose
}
}
----
2023-10-16 11:06:00 +02:00
==== Compliant solution
2023-10-16 11:06:00 +02:00
[source,csharp,diff-id=1,diff-type=compliant]
----
var l = new List<int>();
var o = new object();
var ints = new [] {1, 2, 3};
ints = new [] {1, 2, 3};
int? i = 5;
var j = new int?(5);
Func<int, int> f1 = (i) => 1;
class Class
{
private event EventHandler MyEvent;
public Class()
{
MyEvent += (a,b)=>{ };
}
}
----
2023-10-16 11:06:00 +02:00
== Resources
=== Documentation
2023-10-16 11:06:00 +02:00
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/declarations[Declaration statements]