I have recently started learning c# and have come across an issue. I’m not very familiar with the abstract/interface classes yet do understand the basic principles and applications.
I am Currently looking at OOP for c#, I already know the mechanics of OOP, having done it in Java, yet have never used abstract or interface classes there either.
The aim of my code is to pass in an ArrayList of Objects (Both Children of a Common Parent Class) and Print out only those Objects that are of that particular Class. This works, but I was curious to see If I could get the same method to print out all the child Objects of the parent class, If the parent class is abstract.
Parent Class
abstract class Person
{
protected string Name { get; set; }
protected int Age { get; set; }
public override string ToString() { return "Person:" + Name + ", " + this.Age; }
}
Child Class
class Student : Person
{
private int studID { get; set; }
private string school { get; set; }
public Student() { }
public Student(string name, int age, int studID, string school)
{
this.Name = name;
this.Age = age;
this.studID = studID;
this.school = school;
}
public override string ToString()
{
string s = "Student:" + Name + ", " + Age + ", " + studID + ", " + school;
return s;
}
}
Method Call
private static void StudentDetails(object type)
{
ArrayList tmp = new ArrayList();
//display all
//foreach (Person p in people) tmp.Add(p);
foreach (Person p in people)
{
if (type.GetType() == p.GetType())
{
tmp.Add(p);
}
}
//etc...
Don’t compare GetType() because it doesn’t check for inheritence and stuff.
Check the IsAssignableFrom method -> http://msdn.microsoft.com/de-de/library/system.type.isassignablefrom.aspx, this is what you are looking for.