Maha

Maha

  • NA
  • 0
  • 328.4k

Casting

Sep 6 2012 9:49 PM
I wish to know whether my understanding about casting is correct.

In the following program even though we declare payingStudent object type is the Student type and freeStudent object type is ScholarshipStudent type, if we want to get the type of the object we have to get it from the underlying System.Object class because every class we create derives from a single class named System.Object. In other words, the object (or Object) class type in the System namespace is the ultimate base class for all other types.

Only through casting we can get relevant object type from the underlying System.Object class that is why casting is necessary.

using System;

class DemoStudents4
{
public static void Main()
{
Student payingStudent = new Student();
ScholarshipStudent freeStudent = new ScholarshipStudent();

payingStudent.SetName("Megan");
payingStudent.SetCredits(15);

freeStudent.SetName("Luke");
freeStudent.SetCredits(15);

Console.WriteLine(((object)payingStudent).ToString());
Console.WriteLine(((object)freeStudent).ToString());

Console.ReadKey();
}
}

class Student
{
private string name;
protected int credits;

public void SetName(string name)
{
this.name = name;
}
public void SetCredits(int creditHours)//SetCredits in the child class as well
{
credits = creditHours;
}
public new string ToString()
{
string stuString = "Student " + name + " has " + credits + " credits";
return stuString;
}
}

class ScholarshipStudent : Student
{
new public void SetCredits(int creditHours)
{
credits = creditHours;
}
}
/*
Student
ScholarshipStudent
*/

Answers (6)