A property is a member that provides a flexible mechanism to
read, write or compute the value of a private field. We can use concept of
property when we want to get and set any value in objects member. It is better practice
that does not allow accessing your variables directly. If you want to get value
from any variable or want to set any value to a variable then we can use
concept of property. Property is also known as indexer.
We can use get and set keyword to create a property in c#. Depending upon programming
requirements we can create three types of property.
1)
Read only property:
Such type of property which is created by using get
keyword is called read only property. We cannot initialize any new value to
read only property. For creating read only property we can use following syntax
<access-specifier>
<return-type> <propery-name>
{
get
{
//Statement
to be executed.
return
<return-value>;
}
}
2)
Write only property:
Such type of property which is created by using set keyword
is called write only property. We cannot access any value from write only
property. We can only initialize new value in write only property. For creating
write only property we can use following syntax.
<access-specifier> <return-type>
<propery-name>
{
set
{
//Statement
to be executed.
}
}
3)
Read-Write
property: Such type of property which is created by using get and set keyword
is called read-write property. We can access value as well as initilize new
value to a variable by using Read-Write property. For creating read-write
property we can use following syntax.
<access-specifier> <return-type>
<propery-name>
{
get
{
//Statement
to be executed.
return
<return-value>;
}
set
{
//Statement
to be executed.
}
}
Following example demonstrate use of property in c#
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
PropertyDemo
{
class Program
{
private
string _message;
static void Main(string[]
args)
{
Program
pr = new Program();
//Calling
write only property.
pr.SetMessage = "This is writeonly property.";
//Calling
read only property
Console.WriteLine(pr.GetMessage);
//Calling
read-write only property.
pr.Message = "Hello...";
Console.WriteLine(pr.Message);
Console.ReadLine();
}
//Creating
read only property.
public string GetMessage
{
get
{
return
"This is readonly property.";
}
}
//Creating
write only property.
public string SetMessage
{
set
{
Console.WriteLine(value);
}
}
//creating
read-write property.
public string Message
{
get
{
return
_message;
}
set
{
_message = value;
}
}
}
}
Output:
This is writeonly property.
This is readonly property.
Hello...