Create Instance

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
 
S

Sharon

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top