Reputation: 46425
I have a method where I want to have a parameter that is a Type, but of a certain interface.
E.g.:
public static ConvertFile(Type fileType)
where I can specify fileType inherits IFileConvert.
Is this possible?
Upvotes: 2
Views: 148
Reputation: 754763
Expanding on Marc's answer. He is correct, without generics there is no way to enforce this at compile time. If you can't or don't want to use generics, you can add a runtime check as follows.
public static void ConvertFile(Type type) {
if ( !typeof(IFileType).IsAssignableFrom(type)) {
throw new ArgumentException("type");
}
...
}
Upvotes: 0
Reputation: 115751
If you want to enforce that at compile-time, generics are the only way:
public static ConvertFile<T>(T fileType)
where T : IFileType
To check at run-time, you can do:
Debug.Assert(typeof(IFileType).IsAssignableFrom(fileType));
Upvotes: 1
Reputation: 1062865
One option is generics:
public static ConvertFile<T>() where T : IFileConvert
{
Type type = typeof(T); // if you need it
}
and call as:
ConvertFile<SomeFileType>();
Upvotes: 4
Reputation: 422006
Nope, it's not possible. However you could do:
public static void ConvertFile<T>() where T : IFileConvert {
Type fileType = typeof(T);
}
instead.
Upvotes: 3
Reputation: 14057
Can't you just do:
public static ConvertFile(IFileConvert fileType)
Upvotes: 0