I'm experimenting a bit with the Roslyn-CTP.
Currently I'm trying to replace var
with the concrete type.
var i=1;
should become:
int i=1;
Figuring out the inferred type is easy. But since this part happens in the semantic model I get a ITypeSymbol
. The replacement happens in the syntax model, so I need a TypeSyntax
. Since I don't want a bloated name (global::System.Int32
), the conversion is context dependent (using
, nested types etc.).
The Visual studio version that's part of Roslyn already has this functionality in its "Simplify type name" quickfix, but looking over the samples I couldn't find an easy way to do this conversion.
Based on Kevin Pilch-Bisson's answer I'm now using:
var location = document.GetSyntaxTree().GetLocation(node);
string name = variableType.ToMinimalDisplayString((Location)location, (SemanticModel)document.GetSemanticModel());
A location which ToMinimalDisplayString
can be obtained from a CommonSyntaxTree
.
An additional complication is that ToMinimalDisplayString
requires the classes Location
and SemanticModel
, whereas document.GetSemanticModel()
and CommonSyntaxTree.GetLocation
only return an interface.
I worked around by simply casting to the classes, which seems to work for now.
Hmm it looks like the classes are C# specific, and the interfaces language independent.
I've uploaded a working version on github: https://github.com/CodesInChaos/Roslyn
It doesn't work for var
in a foreach
, but I suspect that's a limitation of the current Roslyn build.
You can get the shortest legal string to represent a symbol at a given location using the ToMinimalDisplayString()
extension method that applies to ISymbol
(note: It's found in `Roslyn.Compilers.CSharp.SymbolDisplay.
Disclaimer: I work at Microsoft on the Roslyn team.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With