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
*/
Loading

VulpesRank #55 · 29.2K reputationPosted Sep 7, 2012, 5:30 AM EDT
The ToString() method of the System.Type class also returns the fully qualified name of the type.
If you pass Console.WriteLine something which isn't a string then it automatically calls its ToString() method.
So, if you pass it payingStudent.GetType(), then payingStudent.GetType().ToString() gets called which is why the output is the same whether you use the FullName property or not.
Sukesh MarlaRank #461 · 5.4K reputationPosted Sep 6, 2012, 7:18 PM EDT
but what do u mean by
Only through casting we can get relevant object type from the underlying System.Object class that is why casting is necessary.
Posted Sep 6, 2012, 7:42 PM EDT
VulpesRank #55 · 29.2K reputationPosted Sep 7, 2012, 12:50 AM EDT
Posted Sep 7, 2012, 4:28 AM EDT
Console.WriteLine(payingStudent.GetType().FullName); // Student
Console.WriteLine(freeStudent.GetType().FullName); // ScholarshipStudent
Posted Sep 7, 2012, 5:34 AM EDT