Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if a class/type is defined prior to compiling

This is similar to a few other threads i have found, but I haven't found the answer I need yet. I would appreciate a direct answer, even if it is "no, you can't do that".

Is there a way to use one block of code if a class/type exists and another if it doesn't. The result would be the same as using preprocessor directives but without the need to #define and manually comment or un-comment something in a file.

This may be a special use-case. I'm not sure. I'm working in an environment where sets of files can be installed, or not, before anything is compiled. So someone could buy a plugin which gets "installed" (files added to the project) which makes classes/types available for use (like extending an API). I need to provide a workaround if someone doesn't have one of our other plugin packages. I hope that makes sense.

It just wouldn't be user-friendly to ask someone to open up one of our files, if they have another plug-in, to un-comment a preprocessor directive, unless we have to.

e.g. I know this doesn't work because it only tests boolean if #define is used, but it illustrates what I am trying to do...

#if SomeType
    SomeType.DoSomething();
#else
    DefaultWay.DoSomething();

EDIT: I added this as a C# feature suggestion. Please vote here: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2297494-add-type-testing-as-preprocessor-directive

I don't see how reflection would be able to do this, but I am new to C#, so examples using relection, if it is possible, would be great.

like image 546
Rafe Avatar asked Oct 05 '11 02:10

Rafe


1 Answers

Instead of using pre-compiler statements (which I don't know if they would work anyway if the client didn't have to recompile after installing your plug-in), I would suggest querying the assembly and trying to instantiate an instance of the class by string as seen here:

C# - Correct Way to Load Assembly, Find Class and Call Run() Method

Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll"); 
Type     type     = assembly.GetType("TestRunner");  

if (type != null)
    //Do Something

Editing to show Activator call

if type is not null then use this to create an instance of the type you want.

var      obj      = Activator.CreateInstance(type); 
like image 52
Rikon Avatar answered Nov 03 '22 00:11

Rikon