Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a public getter and a private setter with same name possible in C#?

Tags:

c#

properties

How can I create a public getter and a private setter for a property? Is the following correct?

public String Password {     set { this._password = value; } }  private String Password {     get { return this._password; } } 
like image 906
BlueBird Avatar asked May 21 '11 15:05

BlueBird


People also ask

Can getters and setters be private?

The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.

Can getters and setters be public?

In general, they should be public. If they are private they can only be called from within your class and, since you already have access to the private variables within your class, are redundant. The point of them is to allow access to these variables to other, outside, objects.

Should getters and setters be public or private?

Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.

Is it important to always define setters and getters for all the private variables?

It is not necessary to write getter or setter for all private variables. It is just a good practice. But without any public function you can not access the private data(variable) of the class.


1 Answers

Yes it is possible, even with auto properties. I often use:

public int MyProperty { get; private set; } 
like image 179
Anders Abel Avatar answered Oct 02 '22 11:10

Anders Abel