Muneer
Muneer

Reputation: 7564

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

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; }
}

Upvotes: 52

Views: 54816

Answers (6)

Tahbaza
Tahbaza

Reputation: 9548

public string Password { get; private set; }

Upvotes: 2

Marc Wittke
Marc Wittke

Reputation: 3155

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; }

Upvotes: 1

YetAnotherUser
YetAnotherUser

Reputation: 9346

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

Upvotes: 2

Cody Gray
Cody Gray

Reputation: 244722

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; }
}

Upvotes: 14

Jason Moore
Jason Moore

Reputation: 3374

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; }

Upvotes: 5

Anders Abel
Anders Abel

Reputation: 69260

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

public int MyProperty { get; private set; }

Upvotes: 121

Related Questions