oop - Create a C# method that accepts multiple types of objects? -


i writing class handle data transactions. want create method handle multiple objects instead of having different method every object type.

for example, have object types: car, truck, house. each object has property holding names of fields , types should go in creating database. likewise, each object has method called printfieldswithtype() print out part of sql query.

i've been trying like:

private void createtable(string tblname, object tempobject)     {         //construct command string params         string mycommand = "create table " + tblname + tempobject.printfieldswithtype();         tempobject = null;         //construct object , execute query         command = new sqlitecommand(mycommand, myconnection);         command.executenonquery();     } 

instead of creating different method each object type, able call method like: createtable(newcars, car mycar); createtable(cheaphouses, house myhouse);

am attempting handle wrong way?
there better way this?

thanks in advance help.

am attempting handle wrong way?

yes, because object not contain definition printfieldswithtype code not compile.

is there better way this?

create interface defines properties/methods common types:

public interface ithing //(please come better name) {     public string printfieldswithtype(); } 

and have each type implement interface:

public class car : ithing 

etc.

then change createtable to

private void createtable(string tblname, ithing tempobject) 

if implementation of printfieldswithtype exactly same each type can make base class instead of interface, since class can have 1 direct base class can implement multiple interfaces, need choose wisely.


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -