Tuesday 6 March 2012

Calling Base Class Constructor/ Use of Base Keyword in c#


// Inheritance Calling Base Class Constructors
using System;
class Person
{
//Private data declaration
string firstName,lastName;
int age;
Gender g;

//Declaring Enumeration
public enum Gender{Male,Female};

//Constructors
public Person(string firstName,string lastName,int age,Gender g)
{
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
this.g=g;
}

//override ToString() Method
public override string ToString()
{
return firstName+" "+lastName+" "+age.ToString()+" "+g.ToString();
}
}

class Manager:Person
{
string phoneNo,officeLocation;

//Initializing Private data By calling Base Class Constructors
public Manager(string firstName,string lastName,int age,Gender g,string phoneNo,string officeLocation): base (firstName,lastName,age,g)
{
this.phoneNo=phoneNo;
this.officeLocation=officeLocation;
}

//override ToString() Method
public override string ToString()
{
return base.ToString()+" "+phoneNo+" "+officeLocation;
}
}

class Program
{
static void Main()
{
Manager obj=new Manager("Ankur","Bhatnagar",26,Person.Gender.Male,"9014250447","Ameerpet");
Console.WriteLine(obj);
}
}

No comments:

Post a Comment