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
VulpesPosted Sep 7, 2012, 9:30 AM
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.
Posted Sep 7, 2012, 9:34 AM
Posted Sep 7, 2012, 8:28 AM
Console.WriteLine(payingStudent.GetType().FullName); // Student
Console.WriteLine(freeStudent.GetType().FullName); // ScholarshipStudent
VulpesPosted Sep 7, 2012, 4:50 AM
Posted Sep 6, 2012, 11:42 PM
Sukesh MarlaPosted Sep 6, 2012, 11:18 PM
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.