TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Maha
NA
0
326k
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
*/
Reply
Answers (
6
)
C# process code
csharp