Create Instance

  • Thread starter Thread starter Islam Elkhayat
  • Start date Start date
I

Islam Elkhayat

I have to 2 Data classes have the same methods with defferent implemention
which work with 2 tables in the database..
I want to chnge the instance referance depend on if condition or switch
case..
like this...

myclass.AddRow()

where my class can be instance of Categories or Employees so i don't have to
write the same code twice..
I tried Activator.CreateInstance(); which return an object but i couldn't
access methods..
Is there a way to make it work??
thanx
 
You can use polymorphism.
Create an interface or an abstract class A.
Then make classes B and C implement or inherit A.
At run time you can create a new instance like this:

if(condition)
{
A instanceName = new B();
}
else
{
A instanceName = new C();
}

The rest of the code simply relates to A,
activating a different method according to the instance type.

If you choose an abstract class, you need to declare
methods as virtual, and override them.
 
Back
Top