I have WCF with DataContract defined and a few other DataContract that extend it. So it looks something like this in it’s primitive form:
[DataContract(Name = "FacilityPerson"]
[KnownType(typeof(Student))]
[KnownType(typeof(Teacher))]
public class Person
{
[DataMember(IsRequired=true)]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public DateTime? DOB { get; set; }
}
[DataContract]
public class Student
{
[DataMember(IsRequired=true)]
public int StudentID { get; set; }
}
[DataContract]
public class Teacher
{
[DataMember(IsRequired=true)]
public int StaffID { get; set; }
}
I have a ServieContract that has only one operation and looks like this:
[OperationContract(Name = "ReportNewPerson")]
void ReportNewTeacherOrStudent(Person person);
My problem is when I am implementing it, I can’t access children properties of a parent object.
public class UniversityService : IUniversityServiceContract
{
void ReportNewTeacherOrStudent(Person person)
{
if(person.GetType().FullName == "Student")
{
//here I have a parent object so I cannot getStudentId which is a child property
Console.Writeline(person.StudentId);
}
}
}
What should I do here?
Don’t compare the type from the name; instead, use a cast or the
asoperator to do that: