org.sonar.plugins.csharp.S3257.html Maven / Gradle / Ivy
Why is this an issue?
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.
Additionally, initializations providing the default value can also be omitted, helping to make the code more concise and readable.
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.
How to fix it
Remove any unneeded code. C# provides many features designed to help you write more concise code.
Code examples
Noncompliant code example
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?
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
}
}
Compliant solution
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)=>{ };
}
}
Resources
Documentation
- Microsoft Learn - Declaration
statements