Consider the following analyzer:
public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
{
var throwStatement = node as ThrowStatementSyntax;
var isObjectCreationExpression = throwStatement.Expression is ObjectCreationExpressionSyntax;
var obj = throwStatement.Expression as ObjectCreationExpressionSyntax;
var isCorrectTypeOfExpression = (obj.Type as IdentifierNameSyntax).Identifier.Text == typeof(ArgumentException).Name;
}
C SyntaxKind.ThrowStatementas a kind of interest.
objshould be nullif the specified exception was not declared there, in the form new Exception(), but rather presented as throw ewhere ethe previously declared exception is.
This, in turn, will trigger NullReferenceExceptionwhen obj.Typecalled immediately after.
The example in question:
static void Method1()
{
throw new ArgumentException();
}
static void Method2(ArgumentException e)
{
throw e;
}
The first one throwwill only pass the analyzer in a fine, but the second will call objhow null, since it has no type ObjectCreationExpressionSyntax.
In Visual Studio Visual Studio, this will display as an informational message:
"FormattingFixes.EmptyArgumentException.ArgumentExceptionAnalyzer" " ".
, , . 1, .
"" , . - , , , , , 2.
, ?