Tuesday 6 March 2012

Indexers in C#


// Indexers Demonstration

using System;
class Student
{
//Private data declaration with one array variable
int sno,sage;
string sname;
int[] marks;

public Student()
{
marks=new int[3];
sno=1010;
}

//To access sno we created a paroperty Id
public int Id
{
get
{
return sno;
}
}

//To access sage we created a paroperty age
public int Age
{
get
{
return sage;
}
set
{
sage=value;
}
}

//To access sname we created a paroperty Name
public string Name
{
get
{
return sname;
}
set
{
sname=value;
}
}

//We cannot access marks through property because it is of type array.
//So we need to declare indexres for marks
public int this[int index]
{
get
{
return marks[index];
}
set
{
marks[index]=value;
}
}

//To access length of marks array we need to create read-only property
public int GetArrayLength
{
get
{
return marks.Length;
}
}

//To print data
public void printData()
{
Console.WriteLine("\nId: {0}, Name: {1}, Age {2}\n",sno,sname,sage);
}
}

class Program
{
static void Main()
{
Student obj=new Student();
obj.Name="Ankur Bhatnagar";
obj.Age=26;

//To enter Marks of student
for(int i=0;i<obj.GetArrayLength;i++)
{
Console.Write("Enter Marks Of Subject{0}: ",i+1);
obj[i]=int.Parse(Console.ReadLine());
}

//To Print The Id,Name and Age Of Student
obj.printData();

//To Print The Marks Of Student
Console.WriteLine("\n-----------------Marks-----------------\n");
int total=0;
for(int i=0;i<obj.GetArrayLength;i++)
{
Console.WriteLine("Marks Of Subject{0} is: {1}",i+1,obj[i]);
total+=obj[i];

}

//To Print total Marks Of Student
Console.WriteLine("\n-----------------Total Marks-----------------\n");
Console.WriteLine("Total Marks: {0}",total);
}
}

No comments:

Post a Comment