I'm trying to get rid of the "#if TRACE" directives in my code, by using the Conditional attribute instead, but can't apply this approach easily to interfaces. I have a way round this but it's pretty ugly, and I'm looking for a better solution.
E.g. I have an interface with a conditionally compiled method.
interface IFoo
{
#if TRACE
void DoIt();
#endif
}
I can't use the conditional attribute in an interface:
// Won't compile.
interface IFoo
{
[Conditional("TRACE")]
void DoIt();
}
I could have the interface method just call a conditional private method in the concrete class:
interface IFoo
{
void TraceOnlyDoIt();
}
class Foo : IFoo
{
public void TraceOnlyDoIt()
{
DoIt();
}
[Conditional("TRACE")]
void DoIt()
{
Console.WriteLine("Did it.");
}
}
This would leave my client code with redundant calls to the 'nop' TraceOnlyDoIt() method in a non-TRACE build. I can get round that with a conditional extension method on the interface, but it's getting a bit ugly.
interface IFoo
{
void TraceOnlyDoIt();
}
class Foo : IFoo
{
public void TraceOnlyDoIt()
{
Console.WriteLine("Did it.");
}
}
static class FooExtensions
{
[Conditional("TRACE")]
public static void DoIt(this IFoo foo)
{
foo.TraceOnlyDoIt();
}
}
Is there a better way to do this?
A trace method shouldn't be appearing on an interface as it's an implementation detail.
But if you're stuck with the interface, and can't change it, then I'd use the #if ... #endif
approach that you started with.
It is a rather savage syntax though, so I sympathise with why you might want to avoid it...