When writing an analyzer, you may need to check whether a property is an auto-implemented property. Several approaches for this exist online. For example, this post uses the syntax tree to check whether the getter and setter have an implementation.
I prefer to avoid using the syntax tree because it depends on C# / VB.NET syntax, which can change as the languages evolve. Instead, you can use the semantic model to work with symbols. The semantic model abstracts the syntax, so the code works with every language supported by Roslyn.
When Roslyn generates a backing field for an auto-implemented property, it annotates that field with the associated property. This information is accessible via IFieldSymbol.AssociatedSymbol. You can therefore iterate over the fields of the containing type to check whether one was generated for the property. If such a field exists, the property is auto-implemented.
C#
static bool IsAutoProperty(IPropertySymbol propertySymbol)
{
// Get fields declared in the same type as the property
var fields = propertySymbol.ContainingType.GetMembers().OfType<IFieldSymbol>()
// Check if one field is associated to
return fields.Any(field => SymbolEqualityComparer.Default.Equals(field.AssociatedSymbol, propertySymbol));
}
If you use the syntax tree API in an analyzer, you can get the IPropertySymbol associated with a PropertyDeclarationSyntax using the semantic model as shown in a previous post:
C#
PropertyDeclarationSyntax node = ...;
SemanticModel semanticModel = context.Compilation.GetSemanticModel(node.SyntaxTree);
IPropertySymbol symbol = semanticModel.GetDeclaredSymbol(node);
var isAutoProperty = IsAutoProperty(symbol);
Roslyn may eventually expose IPropertySymbol.IsAutoProperty as a public API in a future release.
Do you have a question or a suggestion about this post? Contact me!