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
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.
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.
In C# we have the following 4 types of Properties- Read-Only Property, Read-Write Property
Indexer Property & Static Property
This post covered the asymmetric property in c#. Hope you found this article useful. Please provide your feedback in the comments section.
OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…
JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…
The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…
Some of the Key factors that need to consider while architecting or designing a software…
The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…
The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…