Home > c# > Property with getter only vs. with getter and private setter

Property with getter only vs. with getter and private setter

January 27Hits:1

Are these the same?

public string MyProp { get; } 


public string MyProp { get; private set; } 

I mean in both versions the property can be set in its own class but is readonly for other classes?


public string MyProp { get; } - This is introduced in C# 6.0. And such properties are called read-only auto-properties. Assignments to such members can only occur as part of the declaration or in a constructor in the same class. You can read detailed explanation about it in that MSDN article or in Jon Skeet blog. As explained in that article, such property solves four problem automatically:

  • A read-only-defined backing field
  • Initialization of the backing field from within the constructor
  • Explicit implementation of the property (rather than using an auto-property)
  • An explicit getter implementation that returns the backing field

public MyProp { get; private set; } - This means that the property is read-only in the outside of this class, but you can change it's value inside of this class.

By the way, you can set read-only auto-properties value using new auto-initialize syntax which is again introduced in C# 6.0:

public string MyProp { get; } = "You can not change me";

It is equal to this code for the previous versions of C#:

private readonly string myProp = "You can not change me"
public string MyProp { get { return myProp ; } }

Or, this in C# 6.0:

public string MyProp { get; }
protected MyClass(string myProp, ...)
    this.MyProp = myProp;

is equal to this in the previous versions:

private readonly string myProp;
public string MyProp { get { return myProp; } }
protected MyClass(string myProp, ...)
    this.myProp = myProp;

In C# 6.0:

public class MyClass
    public int MyProp1 { get; }
    public int MyProp2 { get; private set; }

    public MyClass()
        // OK
        MyProp1 = 1;
        // OK
        MyProp2 = 2;

    public void MyMethod()
        // Error CS0200  Property or indexer 'MyClass.MyProp1' cannot be assigned to --it is read only
        MyProp1 = 1;
        // OK
        MyProp2 = 2;

In earlier versions of C# the first property does not even compile for this reason:

Error 1 'MyClass.MyProp1.get' must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.

Values of these properties could be defined inside constructor only:

// C#, all versions
private readonly int _foo;
public int Foo
    get { return _foo; }

// C#, version 6+
// actually, this is the same as above, but backing field is generated
// for you by compiler
public int Foo { get; }

Note, that if you know the name of backing field, you can change its value through reflection, thus, this will change result of property getter, but this code will fail, because there is no setter:

typeof(SomeType).GetProperty("Foo").SetValue(bar, 1)

Value of this property could be defined inside any method of declaring type, but also one can easily change it using reflection, without knowledge about backing field, because there is setter:

// this will work fine: typeof(SomeType).GetProperty("Foo").SetValue(bar, 1)
public int Foo { get; private set; }

In other words: the main difference, that first one has get-method only, while the second one has both get- and set- methods.

In the first one no-one can set the properties value, in the second case at least the class itself can change it. Having said this only the first one is a real "read-only"-property.

However consider combining it with a readonly-backend-field:

private readonly string field;
public string MyProp { get { return this.field; } }

Now any attemp to change the value of either the property itself or the backing-field will fail. This is identical to the syntax introduced in C#6 where the baking-field is automatically added to be reradonly:

public string MyProp { get; }

However as you already assumed for other classes both properties work same, meaning are not ment to be modified in any way.


Related Articles

  • Property with getter only vs. with getter and private setterJanuary 27

    Are these the same? public string MyProp { get; } vs. public string MyProp { get; private set; } I mean in both versions the property can be set in its own class but is readonly for other classes? --------------Solutions------------- public string My

  • Why navigation property doesn't populate when its class is private?January 20

    I have this simple model: class Parent { public int Id { get; set; } public virtual ICollection<Child> Children { get; set; } } class Child { public int Id { get; set; } public int ParentId { get; set; } public virtual Parent Parent { get; set; } }

  • Is a private property the same as a public field?June 17

    Will a private property same as a public field? Here is the sample code I wrote to understand this: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GetSet { class Program {

  • subscribing to different events on Property changed if different propertiesFebruary 1

    I have class Step which has a collection of Task i.e List . Step has properties Status , Time . Task also has the same properties. The values of Status and Time for Step need to be updated whenver anyone of the Tasks get their Time or Status changed.

  • add property to many lists rails4February 2

    I want to create property . Then add it on many lists. One Property can be on many list. here is my models: class List < ActiveRecord::Base has_many :propertyships has_many :properties, :through => :propertyships end class Propertyship < ActiveRe

  • Setter property for collectionFebruary 11

    I have a static setter property for a collection, but this does not run when I assign the value. This property does not put the value in a private variable but calls to static method getVariable() and SetVariable(value) to store the value in the data

  • How to Update the bool Property based on Button Visibility in DataGridColumnHeader StyleFebruary 11

    I'm having filter Icon style implemented for the Target Type = DataGridColumnHeader and I attached the Style in DataGrid. My Requirement is to Update the ViewModel bool Property HasFilterIcon to true if any one of the button within the DataGridColumn

  • Step-by-Step Jakarta Tapestry

    Step-by-Step Jakarta TapestryFebruary 2

    The Jakarta Tapestry framework is a hidden treasure of Java web development. It greatly simplifies the work of both web designers and developers. It offers significant convenience by transparently handling much of the boring "plumbing". It even

  • Resources for persuading that photography is not a suspicious activityNovember 23

    I am looking for web resources to help persuade someone that photography is not a suspicious activity and photographers should not be considered a threat. Right now, the discussion is pretty cordial and I'd like to keep it that way, while still being

  • What is the point of properties?March 26

    Here are some arguments for properties and my counter-arguments: Easier to use than writing getter and setter methods Getter and setter method pairs are a code smell. Making it easier to write these is like making it easier to fail a math test by usi

  • Constant DateTime in C#July 28

    I would like to put a constant date time in an attribute parameter, how do i make a constant datetime? It's related to a ValidationAttribute of the EntLib Validation Application Block but applies to other attributes as well. When I do this: private D

  • Simple KVP System with Amazon S3September 5

    A few weeks ago, I wrote about getting started with Amazon's SDK for PHP. This article assumes you're familiar with the basic concepts of using the SDK. Now we're going to build on that knowledge to create something cool: a light, but powerful data s

  • C#-like class propertiesJanuary 13

    I am currently developing a new breed of 3D engine for my upcoming thesis and I really liked the C# properties, but now I am on C++11 for obvious reasons. Since I couldn't find it elsewhere, I tried to write my own property mechanism that shall nicel

  • Best Scoring Boggle BoardApril 26

    I was interested in seeing the answers to this (now defunct) question, but it has never been corrected/improved. Given a set of 6-sided Boggle dice (configuration stolen from this question), determine in two minutes of processing time which board con

  • Are Persistence-Ignorant objects able to implement lazy loading?July 12

    Persistence Ignorance is an application of single responsibility principle, which in practice means that Domain Objects (DO) shouldn't contain code related to persistence, instead they should only contain domain logic. a) I assume this means that the

  • How to determine item ContentType in FormControl (FieldIterator for instance)?January 17

    I've implemented my ListFieldIterator to change the way field controls rendered. I'd like to change the behaviour of form depending on the item content type, but any attempts to determine ContentTypeId from the code returns wrong result. ListFieldIte

  • Lesser-Known "Features" of PHP's OO ModelJuly 19

    The vast majority of today's applications written in PHP are object-oriented, and in general the core OOP concepts are pretty well understood by PHP developers. This article pushes the boundary of your understanding and shows you some tricks, or pote

  • Strategy for keeping secret info such as API keys out of source control?July 21

    I'm working on a website that will allow users to log in using OAuth credentials from the likes of Twitter, Google, etc. To do this, I have to register with these various providers and get a super-secret API key that I have to protect with pledges ag

  • A CSharpish String.Format formatting helperSeptember 5

    A while ago I implemented .net's string.Format() method in VB6; it works amazingly well, but I'm sure there has to be a way to make it more efficient. I'll start by listing a simple class called EscapeSequence: Private Type tEscapeSequence EscapeStri

  • Discriminated-unions in C#September 26

    So I really want to have something similar to discriminated unions in C#. One way to do it is to use a visitor pattern, but it takes half a life to write all broilerplate code by hands. There is another way that would allow me writing a bit less code

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.369 s.