What is Property and why we use it in C#.
A property is a portion that provides a flexible mechanism to read, write, or calculate the value of a private field. Properties can be used as if they are public data members, but they are actually unique methods called accessors.
They are generally known as 'smart fields' in C# society. We know that data encapsulation and hiding are the two fundamental character of any object oriented programming language.In C#, data encapsulation is possible through either classes or structures. By using various access modifiers like private, public, protected, internal etc it is possible to control the accessibility of the class members.
We use get property accessor is used to return the property value, where as set property accessor is used to assign a new value.
We also use value keyword is used to define the value being assigned by the accessor.
Syntax:
They are generally known as 'smart fields' in C# society. We know that data encapsulation and hiding are the two fundamental character of any object oriented programming language.In C#, data encapsulation is possible through either classes or structures. By using various access modifiers like private, public, protected, internal etc it is possible to control the accessibility of the class members.
We use get property accessor is used to return the property value, where as set property accessor is used to assign a new value.
We also use value keyword is used to define the value being assigned by the accessor.
Syntax:
<acces_modifier> <return_type> <property_name>
{
get
{
}
set
{
}
}
Where <access_modifier> can be private, public, protected or internal. The <return_type> can be any
valid C# type.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class MyClass
{
private int x;
public int y
{
get
{
return x;
}
set
{
x = value;
}
}
}
class Demo
{
public static void Main()
{
MyClass mc = new MyClass();
mc.y = 110;
int xVal = mc.y;
Console.WriteLine("result is={0}", xVal);
Console.Read();
}
}
Output: result is=110
{
get
{
}
set
{
}
}
Where <access_modifier> can be private, public, protected or internal. The <return_type> can be any
valid C# type.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class MyClass
{
private int x;
public int y
{
get
{
return x;
}
set
{
x = value;
}
}
}
class Demo
{
public static void Main()
{
MyClass mc = new MyClass();
mc.y = 110;
int xVal = mc.y;
Console.WriteLine("result is={0}", xVal);
Console.Read();
}
}
Output: result is=110

1 Comment
Thanks
Reply