2

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
}
sazr
  • 24,984
  • 66
  • 194
  • 362

2 Answers2

4

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.

shf301
  • 31,086
  • 2
  • 52
  • 86
  • @JakeM - then you can use reflection to check if a type exists. See updated answer. – shf301 Nov 04 '13 at 23:10
  • I would be tempted to put this in an encapsulating class, so that you do not litter your codebase with type checking. In addition, I would name the encapsulating class the same: `TopographySurface`, just in your own namespace. That way when you decide to drop support for 2013 its a simple matter of changing your `using` statements. – Sam Axe Nov 04 '13 at 23:44
0

I depends on if you are using late biding or early biding. Late binding: -no compiling time warnings/errors -only runtime errors

Early biding: -compiler errors -runtime errors

lauCosma
  • 154
  • 10
  • And? how does it answer the question? – L.B Nov 04 '13 at 22:55
  • @lauCosma thanks for the reply but either solution would still involve a runtime error. I guess I could check at runtime if the reference is present? But its better to do at compile time if possible. – sazr Nov 04 '13 at 23:00
  • checkout the following post : http://stackoverflow.com/questions/1111264/can-i-catch-a-missing-dll-error-during-application-load-in-c – lauCosma Nov 04 '13 at 23:06
  • you can try catch the reference... but that would still be at runtime... so i think that the best solution so far is a runtime error. – lauCosma Nov 04 '13 at 23:09