Is it possible to have different access modifiers for get/set property?
Yes, we can have different access modifier for get/set property.- You Cannot specify accessibility modifiers for both accessors (Get and Set) of the property i.e. you can specify accessibility modifiers for either Get or Set, Not for both. Otherwise you will get compilation error.
- The accessibility modifier of the Get or Set accessor must be more restrictive than the property i.e.
- If property access modifier is public then you can specify Get or Set accessor as Protected, Internal, Private.
- If property access modifier is Internal then you can specify Get or Set accessor as Private only.
Example
public class Employee{
string _name = string.Empty;
int _sal;
// Parameterize constructor.
public Employee(string name, int sal)
{
Name = name;
Salary = sal;
}
public int Salary
{
get
{
return _sal;
}
private set
{
_sal = value;
}
}
public string Name
{
get
{
return _name;
}
private set
{
_name = value;
}
}
}
class MyClass
{
static void Main()
{
Employee obj = new Employee("Ram", 1000);
Console.WriteLine("Name = " + obj.Name);
Console.WriteLine("Salary = " + obj.Salary);
Console.ReadLine();
}
}
Output
Name = RamSalary = 1000
In C#, it is possible that we can have same or different access modifier for get/set property.
No comments:
Post a Comment