Properties in C#.Net
Properties |
- Property is a member of a class which we will use to assign the value to a variable as well as which we will use to retrieve the value from variable.
- Property name and variable name should be same.
- But variable name should start with small letter and property name should start with capital letter.
EX:
eno->Variable name
Eno->Property name
Syntax to Define a Property
<accessmodifier><return type><propertyname>
{
get->retrieving the value
}
{
set->assigning given value
}
}
Types Of Properties
1.Read Only Property
It will Contain only get accessor
2.Write Only Property
Contain only set accessor.
3..Read and Write Properties
Contain get accessor and set accessor
Properties are Two types
1.Instance Property
2.Static property
1.Instance Property
while defining a property if we did not use static keyword is called as instance property.
The purpose of instance property is to initialize and to retrieve values to instance variables.
2.Static Property
while defining if we have used static keyword is called as static property.
purpose of static property is o initialize as well as to retrive values from static variables.
EX:
namespace propertyex
{
Class Employee
{
int eno;
String ename;
int age;
static String cmpname;
internal int Eno
{
get
{
return eno;
}
set
{
eno=vaue;
}
}
internal string Ename
{
get
{
return ename;
}
set
{
ename=value;
}
}
internal int age
{
get
{
return age;
}
set
{
while(value<1||value>150)
{
Console.WriteLine("please enter valid age");
value=int.parse(Console.ReadLine());
}
age=value;
}
}
internal static string Cmpname
{
get
{
return cmpname;
}
set
{
cmpname=value;
}
}
}
class Program
{
void main()
{
Employee emp1=new Employee();
Console.WriteLine("enter your empno");
emp1.Eno=int.parse(console.ReadLine());
Console.WriteLine(" the empno is"+emp1.Eno);
Console.WriteLine("enter your empname");
emp1.Ename=int.parse(console.ReadLine());
Console.WriteLine("the empname is"+emp1.Ename);
Console.WriteLine("enter your age");
emp1.Age=int.parse(console.ReadLine());
Console.WriteLine("the age is"+emp1.Age);
Console.WriteLine("enter your company name");
Employee.CmpName=console.ReadLine();
Console.WriteLine("company name is"+Employee..CmpName);
Console.ReadLine();
}
}
}
Purpose Of Property
- Whenever we want to assign the value to a class level variable or whenever we want to retrieve the value from class level variable fro outside the class we can go for property.
- As well as whenever we want to perform validations while assigning the value to class level variable from outside the class we can use property.
0 comments:
Post a Comment