Saturday 10 March 2012

Static Members in C#


//WAP to demonstrate static members
using System;
class Student
{
//Object Level Data Declaration
int sno,age;
string sname;
//Class Level Data Declaration i.e. static
static string cname;

//Constructor to assign Id
public Student(int sno)
{
this.sno=sno;
}

//Read-Only Property for sno
public int Id
{
get{return sno;}
}

//Property for age
public int Age
{
get{return age;}
set{age=value;}
}

//Property for sname
public string Name
{
get{return sname;}
set{sname=value;}
}

//Static Property for cname
public static string CollegeName
{
get{return cname;}
set{cname=value;}
}

//Print method
public void Print()
{
Console.WriteLine("\nId: {0}, Name: {1}, Age: {2}, College: {3}\n",sno,sname,age,cname);
}
}

class Program
{
static void Main()
{
Student.CollegeName="IME";

Student obj1=new Student(1011);
obj1.Name="Ankur Bhatnagar";
obj1.Age=26;
obj1.Print();

Student obj2=new Student(1012);
obj2.Name="Ankit Agarwal";
obj2.Age=27;
obj2.Print();
}
}

No comments:

Post a Comment