Johan Larsson
Johan Larsson

Reputation: 17580

Determine if a property is an auto property

I'm trying to figure out if a property is an auto property i.e. public int Foo { get; set; }

Stared for a while at PropertyDeclarationSyntax and IPropertySymbol but did not find anything.

Guess an alternative is an extension method that evaluates if get & set does not contain any statements is one way but it does not feel very elegant.

Upvotes: 1

Views: 691

Answers (2)

mazin
mazin

Reputation: 395

This blog gives a good explanation:

In summary,

var isExplicitProperty = node
    .DescendantNodesAndSelf()
    .OfType<PropertyDeclarationSyntax>()
    .Any(prop =>
    {
        if(prop.AccessorList != null)
        {
            return prop.AccessorList.Accessors
                .Any(a => a.Body != null || a.ExpressionBody != null);
        }

        // readonly arrow property declaration
        return true;
    });

Based on the internal source code

Upvotes: 2

SLaks
SLaks

Reputation: 887195

Check whether any of the AccessorDeclarationSyntaxes in the PropertyDeclarationSyntax's AccessorList have a non-null Body.

You can see this by looking at any property declaration using the Syntax Visualizer (from the Roslyn SDK extension).

Upvotes: 5

Related Questions