Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.
}
like image 850
Eddie Avatar asked Nov 30 '22 04:11

Eddie


2 Answers

You'd have to either:

  1. Use Reflection to get the property (and throw if it isn't there)
  2. Have a common interface, such as INamed that has a string Name property, that each of the two classes implement
  3. 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).
like image 139
Eilon Avatar answered Dec 05 '22 03:12

Eilon


You can take advantage of dynamic to bypass the compiler, it checks the type at runtime so you don't need to cast:

void Output(dynamic obj)
{
    Console.WriteLine(obj.Name); 
}
like image 28
cuongle Avatar answered Dec 05 '22 03:12

cuongle