Is it possible to do something like that:
class Program
{
static void Main(string[] args)
{
Customer1 c1 = new Customer1();
DoSomething(c1);
Customer2 c2 = new Customer2();
DoSomething(c2);
}
static void DoSomething<T>(T customer)
{
//... code here ...
InitializeCustomer(customer); // <- error indeed :-(
//... code here ...
}
static void InitializeCustomer(Customer1 c1)
{
c1.Reference = 1234;
c1.Name = "John";
}
static void InitializeCustomer(Customer2 c2)
{
c2.Name = "Mary";
c2.Town = "Tokyo";
}
}
class Customer1
{
public int Reference;
public string Name;
}
class Customer2
{
public string Name;
public string Town;
}
I would like to avoid creating 2 "DoSomething" methods and also avoiding to copy the code twice with different method parameters. I thought to use an object as parameter as well but I need to cast after that... Can you advice me?
Thanks.
Since
Customer1
andCustomer2
do not share a common interface, this is not possible.However, you could rework this so they derive from a base class (or interface), and do their own initialization. This would be much cleaner, as well, since it allows each
Customer
to initialize itself, which keeps a cleaner separation of concerns.For example: