I am having a problem bending my mind to situation. I have a class
A
with a method
CreateInternals()
. One of
CreateInternals()
tasks is to create a new B-object. There are several classes of B-object (
B1
,
B2
,
B3
...) but they all implement the interface
IBable
. The type of
B
object to be created is supposed to be passed to
A.CreateInternals()
.
Now I know that I could just have
CreateInternals
accept a
System.Type
parameter
public void CreateInternals(System.Type BToMake)
{
ConstructorInfo cInfo = type.GetConstructor(argTypes);
IBable internalB = (IBable)cInfo.Invoke(new object[]());
...
}
and call it with the appropriate type
A.CreateInternals(typeof(B2));
However, this would not prevent me from calling
CreateInternals
with an invalid type
A.CreateInternals(typeof(C));
and I would not see the error until runtime.
Is there a way to get the compiler to restrict
CreateInternals
to only accept
BToMake
parameters that implement
IBable
? Something like
public voide CreateInternals(System.Type BToMake where BToMake is IBable) {...}
I have the strange feeling that I can do this using generics, but I think I've been staring at the problem for so long that I have brain-lock and the answer just won't come.
Any help would be appreciated.