tags:

views:

98

answers:

5

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?

A: 

Can't you just do:

public static ConvertFile(IFileConvert fileType)
Damien
This involves instantiating the class which I didn't want to have to do
ck
+3  A: 

Nope, it's not possible. However you could do:

public static void ConvertFile<T>() where T : IFileConvert {
   Type fileType = typeof(T);
}

instead.

Mehrdad Afshari
+4  A: 

One option is generics:

public static ConvertFile<T>() where T : IFileConvert
{
     Type type = typeof(T); // if you need it
}

and call as:

ConvertFile<SomeFileType>();
Marc Gravell
And if you don't know the T ahead of time, you can use MethodInfo.MakeGenericMethod to invoke it... trickier, though
Marc Gravell
This will do the job nicely.
ck
+1  A: 

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));
Anton Gogolev
A: 

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");
  }
  ...
}
JaredPar