Simon Edström
Simon Edström

Reputation: 6619

Check if a interface is implemented by a type in compile time

I have a project where I want to keep a reference to a Type and later initalize instance of that type. But I want some compile-time type-checking so I only can provide types that implements the ITest interface. I think I have to change approach, but I can't see how.

private static Type currentType = null;

public static void Initalize (Type current){
     currentType = current;
}

public class Test : ITest{}
public class Test2 {}

It should be possible to pass in the typeof(Test) but not typeof(Test2)

Upvotes: 0

Views: 156

Answers (2)

James
James

Reputation: 82096

You would need to change your Initialize method to:

public static void Initialize(ITest current)

Alternatively, you could use Generics to constrain the type e.g.

public static void Initialize<T>(T current) where T: ITest

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190915

Why dont you use generics?

private static Type currentType = null;

public static void Initalize <T>() where T: ITest {
     currentType = typeof(T);
}

Upvotes: 5

Related Questions