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; }
}
p
public string Password { get; private set; }
To gain an 'Excavator' badge, and to make the answer up to date - readonly fields encapsulated by a get-only property
private readonly int myVal;
public int MyVal get { return myVal; }
may be now (as of C# 6.0) shortened to
public int MyVal { get; }
public String Password
{
private set { this._password = value; }
get { return this._password; }
}
or you can use an auto-implemented property:
public String Password { get; private set; }
public String Password
{
private set { this._password = value; }
get { return this._password; }
}
MSDN:
The get and set methods are generally no different from other methods. They can perform any program logic, throw exceptions, be overridden, and be declared with any modifiers allowed by the programming language.
Edit: MSDN quote is just to clarify why geter and setter can have different access mdofiers, Good point raised by @Cody Gray:
Yes, properties can perform program logic and throw exceptions. But they shouldn't. Properties are intended to be very lightweight methods, comparable to accessing a field. The programmer should expect to be able to use them as they would a field without any noticeable performance implications. So too much heavy program logic is strongly discouraged. And while setters can throw exceptions if necessary, getters should almost never throw exceptions
Yes, as of C# 2.0, you can specify different access levels for the getter and the setter of a property.
But you have the syntax wrong: you should declare them as part of the same property. Just mark the one you want to restrict with private
. For example:
public String Password
{
private get { return this._password; }
set { this._password = value; }
}
Yes it is possible, even with auto properties. I often use:
public int MyProperty { get; private set; }