As the title says, how do I ask Roslyn to generate an identifier for me, similar to how the pattern matching code fixer or the generate method ones do?
Asked
Active
Viewed 92 times
0
-
How to ask ? Politely ! :) The "getHashCode()" does not really generate an identifier ; it "tries" to generate a pseudo-code based on "value" of the object (this last sentence may initiate a lot of debates). To answer, we may need to know what you are trying to achieve exactly. – Romka Jun 07 '21 at 20:54
-
I'm talking specifically about `document1` which is generated by Roslyn based on the type being matched. – Blindy Jun 07 '21 at 21:00
1 Answers
1
Turns out there is an internal class inside Roslyn that does this, but it does much more than what I need.
Instead, I simply used the semantic model to get the list of visible symbols at the start of my block's span, named my identifier the same as my type (just starting with a lowercase letter) and started adding numbers at the end of it until I get something that's not otherwise visible:
var symbols = new HashSet<string>(semanticModel.LookupSymbols(bes.SpanStart).Select(s => s.Name));
var baseIdentifierName = baseType is PredefinedTypeSyntax pts ? pts.Keyword.ValueText : throw new InvalidOperationException();
if (isArray && !baseIdentifierName.EndsWith("s"))
baseIdentifierName += "s";
if (char.IsUpper(baseIdentifierName[0]))
baseIdentifierName = $"{char.ToLower(baseIdentifierName[0])}{baseIdentifierName.Substring(1)}";
var identifierName = baseIdentifierName;
var index = 0;
while (symbols.Contains(identifierName))
identifierName = baseIdentifierName + ++index;

Blindy
- 65,249
- 10
- 91
- 131