c# - Return an object of one class in a generic method -
i have scenario there 2 classes classa , classb methods methoda , methodb respectively. have write generic method returns object instances of above classes depending on condition of integer variable x. when try code below, error says "cannot implicitly convert classa t" or "cannot implicitly convert classb t"
public classa { public void methoda() { //method implementation } } public classb { public void methodb() { //method implementation } } generic method
public t methodgeneric<t>() { int x; classa objecta = new classa(); classb objectb = new classb(); if(x==2) { return objecta; } else { return objectb; } }
the problem t not classa nor classb.
you attempt handle via casting, so:
public static t methodgeneric<t>() t : class { int x = 2; classa objecta = new classa(); classb objectb = new classb(); if (x == 2) { return objecta t; } else { return objectb t; } } however, not protect if calls methodgeneric<classc>(), other returning null in case.
you make safer if have classa , classb both derive same base class or interface, put generic constraint in place reduce chance of error. however, still not safe way of working, generics wouldn't appropriate. might better have interface implemented both classes (ie: iclassbase) , not use generics, return interface:
public iclassbase createinstance() { //... return objecta; // work fine, provided classa implements iclassbase }
Comments
Post a Comment