Passing Generic Input object to a method C# -
i have method abc() gets called 2 different places in application. , both places have different objects of class implemented common interface "idestination".
my 2 classes , interface looking this:
public class classa: idestination { public string var1 { get; set; } public string var2 { get; set; } public string var3 { get; set; } } public class classb: idestination { public string var1 { get; set; } public string var2 { get; set; } public string var3 { get; set; } public string var4 { get; set; } public string var5 { get; set; } } public interface idestination { string var1 { get; set; } string var2 { get; set; } }
as of method abc() accepts object of classa, want can accept object of classb. have made method defination generic below:
public string abc<t>(t obj) { }
but, problem inside abc method want access properties of classes (classa , classb both).
public string abc<t>(t obj) { //some code obj.var2; //of classa obj.var4; //of classb //some code }
and can't allowed changes in interface.
how can achieve this? not want create method handling different class objects. idea?
you should definitly re-think design. when method accepts instances of interface should work all types, not set. imagine create third type implements interface. have re-implement whole method support this. therefor properties should defined on interface instead of class-level , can accessed within method.
however if have use current approach can cast appropriate type:
classa = obj classa; if (a != null) a.var2 = ... // fail if user provides instance of classc implements interface else ((classb)obj).var4 = ...
for work need constraint on gegernic parameter:
public string abc<t>(t obj) t : idestination
Comments
Post a Comment