Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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.
Posted
Updated 22-Apr-11 12:43pm
v3
Comments
Clive D. Pottinger 22-Apr-11 19:31pm    
Thank you, orsobrown. I knew it was something fairly straight-forward, but like I said: brain-lock!

1 solution

2 ways of doing it. If you prefer NOT having to deal with instances of your object as parameters:
XML
public void CreateInternals<T>() where T:IBable
{
    Type theTypeIs = typeof(T);
..
..
..
}

CreateInternals<yourclassname>();
</yourclassname>


Otherwise, if you prefer passing instances as parameters:

XML
public static void CreateInternals<T>(T BToMake ) where T:IBable
{
    Type theTypeIs = BToMake.GetType();
..
..
..
}

CreateInternals(someInstanceImplementingYourInterfaceIBable);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900