X

Adding attribute to backing field of automated property

There are scenarios where developers want to add attributes to backing field of automated property. It was hard to do before C# 7.3. Now it is supported in Visual Studio and solution is simple. This blog post shows how to add attribute to backing field of automated property.

Suppose we have a class with automated property and we want to apply some attribute to backing field of this property. Also let’s suppose this attribute can be used only with fields.

public class AttributeOnBackingFieldDemo
{
    public string SomeProperty { get; set; }
}

[AttributeUsage(AttributeTargets.Field)]
public class FieldOnlyAttribute : Attribute
{
}

With previous versions of C# it was not possible to add attribute like this to backing field of automated property.

Adding backing field attribute

With C# 7.3 we can do it and it’s actually simple. For automated properties we can use field keyword with attribute to specify that attribute is applied directly to backing field like shown here.

public class AttributeOnBackingFieldDemo
{
    [field: FieldOnly]
    public string SomeProperty { get; set; }
}

[AttributeUsage(AttributeTargets.Field)]
public class FieldOnlyAttribute : Attribute
{
}

When opening compiled example in decompiler we can see the following code.

public class AttributeOnBackingFieldDemo
{
    [CompilerGenerated]
    [FieldOnly]
    private string <SomeProperty>k__BackingField;

    public string SomeProperty
    {
        get
        {
            return this.<SomeProperty>k__BackingField;
        }
        set
        {
            this.<SomeProperty>k__BackingField = value;
        }
    }

    public AttributeOnBackingFieldDemo()
    {
        base..ctor();
    }
}

Backing field has still CompilerGenerated attribute applied but additionally there is also our FieldOnly attribute.

Wrapping up

There are advanced scenarios when developers want to apply attribute directly to backing field. These scenarios cover some aspects of unit testing and serialization by example. In previous versions of C# it wasn’t possible to add attribute to backing field without modifying compiled assembly using Intermediate Language tools and building assembly again. In C# 7.3 it is easy to add attribute to backing field of automated property – we apply attribute to automated property and use field keyword to tell compiler that attribute is for backing field.

Liked this post? Empower your friends by sharing it!
Categories: C#

View Comments (0)

Related Post