I have an interface for specifying GetData method which returns one instance of the class by its ID
public interface ILabelData<T> {
T GetData(object id);
}
and also have many different classes those who implements the interface and having members of course:
public class BTAC : ILabelData<BTAC> {
// members...
// and interface impl:
public BTAC GetData(object id) {
return null;
}
}
public class KTAC : ILabelData<KTAC> {
// members...
// and interface impl:
public KTAC GetData(object id) {
return null;
}
}
Within a calling method I would like to instantiate a BTAC/KTAC/... class and call their GetData method. (The purpose of it is becasue after I have the required instance I want to get its members and attributes. Getting the members and attributes is not part of my question.)
ILabelData<object> o = Activator.CreateInstance(type, new object[] { myID });
^^^^^^^^^^^^^^^^^^^^
object data = o.GetData(myID);
the problem is compiler error Cannot implicitly convert type 'object' to 'ILabelData< object >'
After instantiating the proper class of course I do need for the members and attributes, too, so it isn't enough to getting back ILabelData typed object.
How can I get a such kind of object? Some factory or whatever?
GetData
be an instance method onBTAC
.Activator.CreateInstance
returnsobject
- you need to explicitly cast it to the type you want.ILabelData<object>
.The thing is, with the code as is, there's no point in having
ILabelData
generic at all! If you're going to work withobject
anyway, remove the generic parameter fromILabelData
and just do this:Having the interface (and
GetData
method) generic only makes sense if you actually use it that way.If you usually use it directly, and you only need it like this in a few special cases (why?) you could also make the interface covariant:
This will allow you to implement
ILabelData<BTAC>
inBTAC
, giving you the "user friendly"BTAC GetData(object)
method, while still allowing you to do the explicit cast toILabelData<object>
. Even then, I'd avoid this approach. It smells.