How can I use the same function for different type parameters which have the same member?

c#

Solution

You'd have to either:

- Use Reflection to get the property (and throw if it isn't there)

- Have a common interface, such as `INamed` that has a string `Name` property, that each of the two classes implement

- Declare a local variable as `dynamic` and use it to access the `Name` property (but in effect this is the same as #1, because the dynamic dispatch will merely use Reflection to get the `Name` property).

Problem

BHere is the sample code, I've defined two classes. How can I use the `Output` function to output the member which has the same name in two different classes? ``` class A { public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } public A(string name, int age, string email) { Name = name; Age = age; Email = email; } } class B { public string Name { get; set; } public int Age { get; set; } public string Location { get; set; } public B(string name, int age, string location) { Name = name; Age = age; Location = location; } } void Output(object obj) { // How can I convert the object 'obj' to class A or class B // in order to output its 'Name' and 'Age' Console.WriteLine((A)obj.Name); // If I pass a class B in pararmeter, output error. } ```

Original source