Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can separate access modifiers be specified for the get and set accessors of a property?

Can we specify the access modifiers for the get and set accessors of property in C#/.NET?

If so, what would be the best approach to implement this?

like image 946
Sukhjeevan Avatar asked Jan 20 '11 11:01

Sukhjeevan


People also ask

Can we have different access modifiers on Get set methods of a property?

IS it possible to have different access modifiers on the get/set methods of a property? No. The access modifier on a property applies to both its get and set accessors.

Are getters and setters access modifiers?

The answer is Yes! We can access the private access modifiers outside the class with the help of getters and setters.

What are property accessors?

A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.

Why use get set instead of public?

The main difference between making a field public vs. exposing it through getters/setters is holding control over the property. If you make a field public, it means you provide direct access to the caller. Then, the caller can do anything with your field, either knowingly or unknowingly.


2 Answers

Yes, this is possible. It is called Asymmetric Accessor Accessibility, and you can read the MSDN documentation for it on this page. The code would look something like this:

public int Age
{
    get
    {
        return _age;
    }
    protected set
    {
        _age = value;
    }
}

However, there are a couple of important caveats to keep in mind:

  • Only one accessor can be modified.
  • Any restrictions placed on an individual accessor must be more restrictive than the accessibility level of the property itself, not less.
  • You cannot use accessor modifiers on an interface or an explicit implementation of an interface member.
like image 134
Cody Gray Avatar answered Nov 03 '22 07:11

Cody Gray


Yes you can...

public class Example
{
    public string Property
    {
        get;
        private set;
    }

    public string Property2
    {
        get;
        protected set;
    }
}

etc.

like image 23
WraithNath Avatar answered Nov 03 '22 07:11

WraithNath