Is it possible to force an auto-property to use a readonly backing field?

I'm afraid not, but you can do this:

public string LastName { get; private set; }

Not quite as good as readonly, but not too bad.


No, unfortunately there's no way of doing this. Personally there are two things that I think are missing from automatically implemented properties in C# - a default value (which I believe will be in VB10) and readonly properties which can only be set in the constructor. In other words, I'd like to be able to do:

public class Foo
{
    public string Tag { get; internal set; } = "Default value";

    // The "readonly" would imply "private" as it could only
    // be set from a constructor in the same class
    public int Value { get; readonly set; }

    public Foo()
    {
        // Valid to set property here, but nowhere else
        Value = 20;
    }
}

As Jared mentioned, this would mean changing compiler calls to the property setter into simple field assignments, and making sure they only occurred in the constructor.

This would make writing immutable types simpler. Unfortunately the situation won't improve in C# 4. Let's hope we get something like this for C# 5...


No it is not and if it was the feature would be useless without significant tweaking.

A readonly field can only be verifiably set from a constructor. A auto-implemented property can only be set from the generated setter. These are incompatible requirements and will produce unverifiable code.

Yes you could potentially make the compiler smart enough to ignore the setter and go straight to the backing field in the constructor. But in the setter itself would still be unverifiable. The compiler would need to omit it from the generated code as will producing a truly read-only property. This produces another contradiction because you would still need to do an assignment statement against the property.

Foo() {
  SomeProperty = "somevalue";
}

In this case the code looks like it's calling a setter on a property. But there is actually no setter to be called since it must be omitted from the final code.

EDIT

This is not saying it can't be done. It can but it would require a bit of work from C#.

In particular they would have to provide a way to set the backing field of a property which cannot have a setter. There are several ways this could be done.

  • Give users access to the backing field of an auto-implemented property
  • Allow the setter style syntax even though there is no setter and let the compiler translate it to a field access under the hood
  • Invent some new syntax

I'm not saying any of these are good options, just possibilities to make this type of feature work .


As of C# 6.0 the answer is yes. Your example can be written as below, and the compiler automatically generates a read-only field behind the property. This is called a getter-only auto-property.

public string LastName { get; }

From https://msdn.microsoft.com/en-us/magazine/dn879355.aspx

Getter-only auto-properties are available in both structs and class declarations, but they’re especially important to structs because of the best practice guideline that structs be immutable. Rather than the six or so lines needed to declare a read-only property and initialize it prior to C# 6.0, now a single-line declaration and the assignment from within the constructor are all that’s needed. Thus, declaration of immutable structs is now not only the correct programming pattern for structs, but also the simpler pattern—a much appreciated change from prior syntax where coding correctly required more effort.


I prefer the real readonly backing field, since this guarantees that I'm not changing that backing field after construction.


Comments

  1. Jameson

    • 2016/1/22

    or you could manually create a private readonly backing field for the I was able to generate a delegate using LINQ Expressions that 

  2. Jon

    • 2017/8/17

    A readonly field can only be verifiably set from a constructor. A auto-implemented property can only be set from the generated setter. These are incompatible requirements and will produce unverifiable code. Yes you could potentially make the compiler smart enough to ignore the setter and go straight to the backing field in the constructor.

  3. Karter

    • 2020/12/15

    For an auto-implemented property in C#, the complier creates a private, anonymous backing field accessed only through get and set accessors 

  4. Rene

    • 2015/9/2

    If you have a readonly "_id" backing field then it would not be possible to write a method to mutate the value*. * (Without resorting to the sort of shenanigans that we are going to look at here) So the second class is more reliable and more accurately conveys the author's intentions for the code (that the "Id" property of an Example instance

  5. Valentini

    • 2016/11/26

    private readonly MyType myProperty; public MyType MyProperty { get { return di Is it possible to force an auto-property to use a readonly backing field?

  6. Colter

    • 2016/4/16

    InvalidOperationException: The specified field '_relatedEntities' of type 'IList' cannot be used for the property 'MyEntity.RelatedEntities ' of type 'IReadOnlyList'. Only backing fields of types that are assignable from the property type can be used. Could you provide a working example how to deal with this issue ?

  7. Jaxxon

    • 2018/2/5

    all properties that fit certain criteria. But months ago I tried to force the automapper to auto-dynamically map to readonly backing fields, 

  8. Franco

    • 2015/10/16

    When a property is specified like this, a backing field will automatically be generated for the property, and the accessors will be implemented to read from and write to that backing field. The name of the backing field is compiler generated and inaccessible to the user. Thus, there is no way to access fields. Utilize your first approach. Auto-implemented properties are specifically for the case where you don't need to access backing field.

  9. Maxton

    • 2018/4/8

    Fields scoped to a property should be implicitly private, and could be marked readonly if the set accessor is not present.

  10. Spencer

    • 2021/3/18

    and the property gets further lowered to a get_layouts1() method. In other words, auto-property initializers are pure syntactic sugar. They provide a means of using auto-properties, whilst still allowing the backing field to be initialised. So from a mutability point of view, there's no difference between them at all.

  11. Hezekiah

    • 2021/3/21

    There are a couple reasons to use private set . 1) If you are not using a backing field at all and want a read-only automatic property:

  12. Harris

    • 2019/2/4

    Access auto property backing field with reflection Using reflection you can easily access any property, filed, methods, pretty much anything of any type in .NET. Reflection is never the most elegant way to do something, but sometime you just have to do it.

  13. Ishaan

    • 2020/2/18

    If yes, remember that auto-properties entail a custom backing field that is backing fields use some specialized characters you are not allowed to use 

  14. Jace

    • 2016/11/30

    The most logical thing I could think to try was to first explicitly map the backing field to a shadow property ala: modelBuilder.Entity<SomeRootClass> ().Property<Identity> ("Identity"); and then use the EF.Property method to tie that to OwnsOne. s => Property (s, "Identity")' is not a valid property expression.

  15. Henrik

    • 2017/1/6

    In this case, properties with backing fields are not highlighted and quick-fixes are tick the Use auto-property, if possible checkbox.

  16. Yadiel

    • 2017/7/22

    Is there any way to access the backing field for a property in order to do validation, change tracking etc.? Is something like the following possible?

Comments are closed.

Recent Posts