Sunday, 24 June 2012

C# Properties : using the getter/setter


C# properties: Properties in C# are used to provide protection to the attributes of a class against direct reading or writing to it . By using properties we fix the rule that a particular attribute of the class can be read or written by means of property associated to that attribute.


These can be classified into 3 types:

  • Read only properties : We implement only the getter in the property implementation.
Syntax:
public String Name
{
get
{
return name;
}
                }
  • Write only properties :We implement only the Setter in the property implementation.
Syntax:
public String Name
{
set{name=value;}
}
  • Auto implemented properties: This is the most commonly used type. we define the both getter and setter without any actual implementation.
Syntax:

public String Name{get; set;}

Example: Accessing the Employee class with properties


Employee.cs
using System;
namespace lab1
{
public class Employee
{
private string name;
private long empid;

public Employee (String Name,long id){ name=Name;empid=id;}
public String Name
{
get
{
return name;
}
set{name=value;}

}
public long Empid
{
get

return empid;
}
set{empid=value;}

}
public override string ToString ()
{
return ("Name:"+name+"\nEmployee ID:"+empid);
}
}
}


Main.cs



using System;
using Gtk;


namespace lab1
{
class MainClass
{
public static void Main (string[] args)
{
Employee E1=new Employee();

E1.Name="kiran";
E1.Empid=1234;

Console.WriteLine("Employee details\n {0}", E1);
Console.WriteLine("End of Employee details",E1);

Console.ReadKey();
}
}
}




No comments:

Post a Comment