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?
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?
Nope, it's not possible. However you could do:
public static void ConvertFile<T>() where T : IFileConvert {
Type fileType = typeof(T);
}
instead.
One option is generics:
public static ConvertFile<T>() where T : IFileConvert
{
Type type = typeof(T); // if you need it
}
and call as:
ConvertFile<SomeFileType>();
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));
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");
}
...
}