meziantou / meziantou.analyzer Goto Github PK
View Code? Open in Web Editor NEWA Roslyn analyzer to enforce some good practices in C#.
License: MIT License
A Roslyn analyzer to enforce some good practices in C#.
License: MIT License
Enumerable.FirstOrDefault
=> Find
Enumerable.IndexOf
=> FindIndexOf
Enumerable.LastIndexOf
=> FindLastIndexOf
public class Foo
{
public virtual void Write(int i = 42)
{
Console.WriteLine(i);
}
}
public class Bar : Foo
{
public override void Write(int i = 5) // Noncompliant
{
Console.WriteLine(i);
}
}
class Base
{
public virtual void Method(params int[] numbers) => { };
}
class Derived : Base
{
public override void Method(int[] numbers) // Error "params" is missing
{
}
}
enumerable.Where(...).OrderBy(...) // compliant
enumerable.OrderBy(...).Where(...) // non-compliant
class SampleAttr : Attribute // Noncompliant
{
}
class Foo : Exception // Noncompliant
{
}
Enumerable.Contains<string>
Enumerable.Distinct<string>
Enumerable.Except<string>
Enumerable.GroupBy<string>
Enumerable.GroupJoin<string>
Enumerable.Intersect<string>
Enumerable.Join<string>
Enumerable.OrderBy<string>
Enumerable.OrderByDescending<string>
Enumerable.SequenceEqual<string>
Enumerable.ToDictionary<string>
Enumerable.ToLookup<string>
Enumerable.Union<string>
partial class A {}
partial static class A {} // Invalid because partial must be just before class
For performance reasons, you should override Equals
and GetHashCode
on value types (struct
).
https://blog.martindoms.com/2011/01/03/c-tip-override-equals-on-value-types-for-better-performance
class Test
{
public static void A()
{
Sample(""); // reported here
}
public static void Sample(string a) { }
public static void Sample(string a, string b) { }
}
sb.Append(string.Join(',', new [] { "a", "b" }));
Should be:
sb.AppendJoin(',', new [] { "a", "b" });
pratices > practices
public delegate void DataReceivedEventHandler(object sender, System.Diagnostics.DataReceivedEventArgs e);
public event System.Diagnostics.DataReceivedEventHandler ErrorDataReceived { add { } remove { } }
It should include a table with the following columns:
Suggest to seal internal class when possible (add an option to seal public class)
public void DoSomething(string fileName)
{
using (var stream = File.Open(fileName, FileMode.Open))
{
var result = new byte[stream.Length];
stream.Read(result, 0, (int)stream.Length); // Noncompliant, should be readLength = stream.Read(...) and readLength should be used
}
}
SyntaxNode: ref coll.FindAsync(filter) [LocalFunctionStatementSyntax]@[6688..6714) (172,12)-(172,38)
System.NullReferenceException: Object reference not set to an instance of an object.
at Meziantou.Analyzer.Rules.ReturnTaskFromResultInsteadOfReturningNullAnalyzer.IsTaskType(Compilation compilation, ITypeSymbol typeSyntax)
at Meziantou.Analyzer.Rules.ReturnTaskFromResultInsteadOfReturningNullAnalyzer.AnalyzeLocalFunction(SyntaxNodeAnalysisContext context)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.<>c__44`1.<ExecuteSyntaxNodeAction>b__44_0(ValueTuple`2 data)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info)
It avoid problems such as
public class Sample
{
private string field;
public Sample(string field)
{
field = field; // Assign parameter instead of field
}
}
BTW, it should also detect assignment of the same variable
var a = 10;
a = a; // Error
Destructors allow to release native resources. You use wrap all native handles in SafeHandle. Thus, you don't need to use a destructor.
if (a == double.NaN) // always return false, should be double.IsNaN(a)
bool condition;
if (condition == true) // should be if (condition)
if (condition == false) // should be if (!condition)
[FlagsAttribute] // Noncompliant, Orange is neither a power of two, nor a combination of any of the defined values
public enum Color
{
None = 0,
Red = 1,
Orange = 3,
Yellow = 4,
}
Calling an overridable method from a constructor could result in failures or strange behaviors when instantiating a subclass which overrides the method.
public class Foo
{
public Foo()
{
VirtualMethod(); // Noncompliant
}
public virtual void VirtualMethod()
{
...
}
}
Skip the validation if the class is sealed
details.Select(o => (Sample)o);
details.Cast<Sample>();
null
if it's an instance eventnull
if it's a static eventEventArgs.Empty
)StartsWith
and EndsWith
, Contains
char
is not available in .NET Frameworkinterface Repository
{
Task FindProduct(string name);
}
public async Task<int> GetId(string name)
{
await Task.Yield(); //Some stuff
var product = _repository.FindProduct(name);
return product.Id;
}
Should be
public async Task<int> GetId(string name)
{
await Task.Yield(); //Some stuff
var product = await _repository.FindProduct(name);
return product.Id; // Or product.Result.Id
}
This one is hard to see/debug 😖😭😆
public void Foo()
{
lock (this) // Error
{
}
}
public void Foo()
{
lock (typeof(Bar)) // Error
{
}
}
class Bar
{
public object public_field;
public void Foo()
{
lock (public_field) // Error
{
}
}
}
This may be an improvement for the current rule: DoNotRemoveOriginalExceptionFromThrowStatement
try
{
}
catch(Exception ex)
{
throw new Exception(); // Should be throw new Exception("", ex);
}
Analyzer 'Meziantou.Analyzer.Rules.DoNotCallVirtualMethodInConstructorAnalyzer' threw the following exception:'
Exception occurred with following context:
Compilation: xxx
SyntaxTree: D:\xxx\QueryResultSchema.cs
SyntaxNode: public QueryResultSchema(string ... [ConstructorDeclarationSyntax]@[480..866) (19,8)-(29,9)
System.InvalidOperationException: Sequence contains more than one element
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at Meziantou.Analyzer.Rules.DoNotCallVirtualMethodInConstructorAnalyzer.AnalyzeConstructorSyntax(SyntaxNodeAnalysisContext context)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.<>c__44`1.<ExecuteSyntaxNodeAction>b__44_0(ValueTuple`2 data)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info)-----'.
--
sample.SampleEvent -= (obj, args) => { }; // error
using System;
namespace myLibrary
{
public class MyExtension : MarkupExtension
{
public MyExtension() { }
public MyExtension(object value1)
{
Value1 = value1;
}
[ConstructorArgument("value2")] // Error, value2 is not a parameter of the constructor
public object Value1 { get; set; }
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.