Checking if a property is an auto-implemented property in Roslyn

  • Gérald Barré

When writing an analyzer, you may want to check if a property is an auto-implemented property. You can find multiple ways to check that on the internet. For instance, this post uses the syntax tree to check whether the getter and setter have an implementation.

I prefer not using the syntax tree as it is dependent on the C# / VB.NET syntax. The languages evolve and thing may change in the future. Instead, you can use the semantic model to work with symbols. The semantic model abstracts the syntax, so the code works with every languages supported by Roslyn.

When Roslyn generates a field for an auto-implemented property, it annotates the field with the associated property. This information is accessible using IFieldSymbol.AssociatedSymbol. This means you can iterate on fields to know if one is generated for the property. If you find one field, the property is an auto-implemented property.

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 to a PropertyDeclarationSyntax using the semantic model as shown in a previous post:

PropertyDeclarationSyntax node = ...;
SemanticModel semanticModel = context.Compilation.GetSemanticModel(node.SyntaxTree);
IPropertySymbol symbol = semanticModel.GetDeclaredSymbol(node);

var isAutoProperty = IsAutoProperty(symbol);

Roslyn will maybe expose IPropertySymbol.IsAutoProperty as a public API or something easier to use in a future release.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee