5

For local declarations like: string a = string.Empty;

How can I write a diagnostic to change it to: var a = string.Empty;

user3500462
  • 125
  • 7
  • You mean no assignment just declaration like `string a;`? – Sriram Sakthivel Apr 22 '14 at 18:44
  • What specifically is tripping you up? This is too broad for a StackOverflow question. Grab the SDK and look at the samples. – Jason Malinowski Apr 23 '14 at 03:08
  • Lucky you, I happened to base my own diagnostic tool on [this project](https://github.com/TheDutchDevil/Halcyon/tree/master/Source/FormattingFixes/TypeToVar) which already implements exactly what you're interested in. – Jeroen Vannevel Apr 23 '14 at 14:40

3 Answers3

7

You can't. The var keyword tells the compiler to perform type inference, and with just var a; the compiler doesn't have enough information to infer a type.

You could however do any of the following

var a = new String();
var b = String.Empty;
var c = "";

but this seems like more effort than it's worth.

Edit for updated request: Why do you want to modify all the code to be declared with var? It compiles to the same IL anyway (trivially simple example):

// var a = String.Empty;
IL_0000:  ldsfld     string [mscorlib]System.String::Empty
IL_0005:  pop
// string b = String.Empty;
IL_0006:  ldsfld     string [mscorlib]System.String::Empty
IL_000b:  pop
Nathan
  • 2,093
  • 3
  • 20
  • 33
4

I've put together a code fix with diagnostic. Here's the interesting parts:

Implementation of AnalyzeNode from ISyntaxNodeAnalyzer

public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
    {
        var localDeclaration = (LocalDeclarationStatementSyntax)node;
        if (localDeclaration.Declaration.Type.IsVar) return;
        var variable = localDeclaration.Declaration.Variables.First();
        var initialiser = variable.Initializer;
        if (initialiser == null) return;
        var variableTypeName = localDeclaration.Declaration.Type;
        var variableType = semanticModel.GetTypeInfo(variableTypeName).ConvertedType;
        var initialiserInfo = semanticModel.GetTypeInfo(variable.Initializer.Value);
        var typeOfRightHandSideOfDeclaration = initialiserInfo.Type;
        if (Equals(variableType, typeOfRightHandSideOfDeclaration))
        {
            addDiagnostic(Diagnostic.Create(Rule, node.GetLocation(), localDeclaration.Declaration.Variables.First().Identifier.Value));
        }
    }

This essentially looks at the types on both sides of the declaration and if they're the same (and the RHS isn't already var) then add a diagnostic.

And here's the code for the Code Fix:

public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
    {
        var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
        var diagnosticSpan = diagnostics.First().Location.SourceSpan;
        var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<LocalDeclarationStatementSyntax>().First();
        return new[] { CodeAction.Create("Use var", c => ChangeDeclarationToVar(document, declaration, c)) };
    }

private async Task<Document> ChangeDeclarationToVar(Document document, LocalDeclarationStatementSyntax localDeclaration, CancellationToken cancellationToken)
    {
        var root = await document.GetSyntaxRootAsync(cancellationToken);
        var variableTypeName = localDeclaration.Declaration.Type;
        var varTypeName = SyntaxFactory.IdentifierName("var").WithAdditionalAnnotations(Formatter.Annotation);
        var newDeclaration = localDeclaration.ReplaceNode(variableTypeName, varTypeName);            
        var newRoot = root.ReplaceNode(localDeclaration, newDeclaration);
        return document.WithSyntaxRoot(newRoot);
    }

This bit is nice and simple, just get var from the Syntax factory and switch it out. Note that var doesn't have it's own static method in the SyntaxFactory so instead is reference by name.

rh072005
  • 720
  • 6
  • 15
  • Exactly what I was looking for ... the only thing I was missing was: var root = await document.GetSyntaxRootAsync(cancellationToken); what is this used for? – user3500462 Apr 24 '14 at 04:56
  • This gets the main block of syntax from the document and contains all of the nodes. It is then used lower down to replace the target node with the new one, which returns the whole root with the new node in place. It's like returning a list of nodes so you've got access to the one you want to replace. – rh072005 Apr 24 '14 at 09:11
0

The compiler can't infer the type from that.

You would need to use:

var a = ""; // compiler can see that is type `string`:

or you can do:

string a;
gleng
  • 6,185
  • 4
  • 21
  • 35