c# - Property with getter only vs. with getter and private setter -


are these same?

public string myprop { get; } 

vs.

public string myprop { get; private set; } 

i mean in both versions property can set in own class readonly other classes?

public string myprop { get; } - introduced in c# 6.0. , such properties called read-only auto-properties. assignments such members can occur part of declaration or in constructor in same class. can read detailed explanation in that msdn article or in jon skeet blog. explained in article, such property solves 4 problem automatically:

  • a read-only-defined backing field
  • initialization of backing field within constructor
  • explicit implementation of property (rather using auto-property)
  • an explicit getter implementation returns backing field

public string myprop { get; private set; } - means property read-only in outside of class, can change it's value inside of class.

by way, can set read-only auto-properties value using new auto-initialize syntax again introduced in c# 6.0:

public string myprop { get; } = "you can not change me"; 

it equal code previous versions of c#:

private readonly string myprop = "you can not change me" public string myprop { { return myprop ; } } 

or, in c# 6.0:

public string myprop { get; } protected myclass(string myprop, ...) {     this.myprop = myprop;     ... } 

is equal in previous versions:

private readonly string myprop; public string myprop { { return myprop; } } protected myclass(string myprop, ...) {     this.myprop = myprop;     ... } 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -