In C# the member variables will be exposed by means of Properties. The get and set portions of a property are called accessors.
A normal property definition in C# is as below
privateintproperty1;
publicintProperty1
{
get
{
returnproperty1;
}
set
{
property1 = value;
}
}
Here the property is public and by default, the accessors have the same visibility that of the property to which they belong. So in the above sample both get and set accessors are public by default and hence it is possible to get and set the property value from outside the class publicly.
Table of Contents
Asymmetric Property Accessor C#
It is sometimes needed to restrict access to one of these accessors. In this case, the possibility to make a property read-only is by removing the setter from property definition as below.
public int Property1
{
get
{
return property1;
}
}
But in C# 2.0 it is possible to provide separate access specifier for get and set. For example, if you only want to make a property read-only from outside then you can simply make the setter as private (or internal to restrict setting of property value from outside the project)
privateintproperty1;
publicintProperty1
{
get
{
returnproperty1;
}
private set
{
property1 = value; ;
}
}
All available access modifiers (private, internal, protected and protected internal)can be applied as desired inside the property definition for set and get.
FAQ on C# Asymmetric Property
What are property accessors in C#?
In C#, to expose private fields from a class there introduced certain special kinds of methods called Property. Property Accessors are C# properties’ internal methods. It is possible to make properties read-only, read-write, or write-only. Reading and writing are supported by the read-write property.
What are the different types of properties supported by C#?
In C# we have the following 4 types of Properties- Read-Only Property, Read-Write Property
Indexer Property & Static Property
Summary
This post covered the asymmetric property in c#. Hope you found this article useful. Please provide your feedback in the comments section.
Leave a Reply