Monday, December 21, 2009

Concept Of Property

C# provides the facility to protect a field in a class by reading and writing to it through a feature called properties.C# properties enable this type of protection while at the same time letting one access the property like a field.Thus properties can be used to encapsulate data within a field.
Property allows fields like access to data members,while still providing data encapsulation and security.
Type of Properties
Properties are categorized into four different types which are as follows:-
>Read/Write Properties
Syntax:
[Access_modifier]datatype PropertyName
{
get();
set();
}
>Read only properties
Syntax:
[Access_modifier]datatype PropertyName
{
get();
}
>Write only properties
Syntax:
[Access_modifier]datatype PropertyName
{
set();
}
>Static properties
Syntax:
[Access_modifier]datatype PropertyName
{
get();
set();
}
Example:-
using System;
using System.Collections.Generic;
using System.Text;
namespace PropertyDemo{
//Class fields to store account number,balance and interest earned.
class SavingsAccount
{
private int_accountNumber;
private double_balance;
private double_interestEarned;
//Rate of interest is static because all accounts earn the same interest
private static double_interestRate;
//Constructor initializes the class members.
public SavingsAccount(int accountNumber,double balance){
this.accountNumber=accountNumber;
this.balance=balance;
//Read only AccountNumber property
public int AccountNumber{
get{
return_accountNumber;
} }
//Read only balance property
public double Balance {
get {
if (_balance<0)
Console.WriteLine("No balance available");
return _balance; }
}
//Read/Write InterestEarned property
public double InterestEarned {
get {
return _interestEarned; }
set {
//validating data
if (value<0.0)
Console.WriteLine("InterestEarned cannot be negative");
return ; }
_interestEarned =value; }
}
//Read/Write interestrate static property since all accounts of a particular type have the same interest //rate
public static double InterestRate {
get {
return _interestRate; }
set {
//validating data
if (value<0.0)
Console.WriteLine("InterestRate cannot be negative");
return ; }
_interestRate =value / 100;
} } }
}
class Program {
static void Main(string[] args) {
//Creating an object of SavingsAccount
SavingsAccount objSavingsAccount= new SavingsAccount(12345,5000);
//User interaction
Console.WriteLine(" Enter Interest Earned till now and rate of interest");
objSavingsAccount.InterestEarned=Convert.ToDouble(Console.ReadLine());
SavingsAccount.InterestRate=Convert.ToDouble(Console.ReadLine());
//Saving property is accessed using class name
objSavingsAccount.InterestEarned+= objSavingsAccount.Balance * SavingsAccount.InterestRate;
Console.WriteLine(" Total Interest Earned is :{0}",objSavingsAccount.InterestEarned);
} } }

No comments:

Post a Comment