Search code examples
c#reference

Check if reference is present at compile time


Is is possible to check if a reference is present in a project at compile time in C#?

For example;

public void myMethod()
{
    #if REVIT_DLL_2014
       TopographySurface.Create(vertices); // This function only exists in Revit2014.dll
       // So I will get a compiler if another DLL is used 
       // ie, Revit2013.dll, because this method (Create) wont exist
    #else // using Revit2013.dll
       // use alternate method to create a surface
    #endif
}

What I want to avoid is having 2 separate C# projects to maintain (ie, a Version 2013 and a Version 2014) because they are the same in almost every way except for 1 feature.

I guess my last resort might be (but it would be nicer if the above feature was possible):

#define USING_REVIT_2014

public void myMethod()
{
    #if USING_REVIT_2014
       TopographySurface.Create(vertices); // This function only exists in Revit2014.dll
       // So I will get a compiler if another DLL is used because this method (Create) wont exist
    #else // using Revit2013.dll
       // use alternate method to create a surface
    #endif
}

Solution

  • Do your detection at runtime instead of compile time.

    if (Type.GetType("Full.Name.Space.To.TopographySurface") != null) {
        TopographySurface.Create(vertices);
    }
    else {
        // use alternate method to create a surface
    }
    

    This assumes that as long as TopographySurface is defined then Create exists.