I want to create a method with generic argument person. person can be either Man or Woman but they are just a class not inheriting from any base. VS tells me that there is no definition for Age in T.
public class Man
{
public string Name { get; set; } = "Man Name";
public int? Age { get; set; }
}
public class Woman
{
public string Name { get; set; } = "Woman Name";
public int? Age { get; set; }
}
public class People
{
public string Person<T>(T person)
{
return person.Age;
};
}
I've search and found some solutions Accessing properties of a generic types and it seems like I have to create 2 overloading methods. As they both do the same thing, is there anyway to tell VS that T has a property Age ?
Edit: I cannot change the classes Man & Woman. I'm writing the Person class.
Thanks.
Edit: Based on @Panagiotis Kanavos suggestions in the answer below, I tried the following and it worked. I am now able to assign the 2 different classes' properties to the same variable (_age) and continue processing using 1 class and 1 set of logic without using generic type. I will try this in my actual program. Thanks very much.
public class People
{
public void Person(object person)
{
int? _age = 0;
switch (person.GetType().ToString())
{
case "Man":
var man = person as Man;
_age = man?.Age;
break;
case "Woman":
var woman = person as Woman;
_age = woman?.Age;
break;
}
Console.WriteLine(_age);
}
}