Debug conditional code in class that implements an interface... does it work?

  • Thread starter Thread starter hellosticky
  • Start date Start date
H

hellosticky

I'm creating some logging code, and each one of my classes has an
internal static readonly instance of the logger which various methods
use, e.g.:

interface ILogger
{
void LogDebug(...);
void LogInfo(...);
void LogError(...);
...
}

What I did was to create two classes, one in the case where the Logger
for that class is off, and the other when it is on.

class Logger : ILogger {...}

class NullLogger : ILogger {
[Conditional("DEBUG")]
public void LogDebug(...)
{
}
....
}

Now, my question is, the ILogger instance is assigned at runtime. So,
if I assign the NullLogger at runtime, which has [Conditional("DEBUG")]
will it still for sure not evaluate the parameters passed to the Log
method if it is of type NullLogger?

For example, with Conditional("DEBUG"), the executeLongMethodToGetValue
is not executed.

myLog.LogDebug(myObj.executeLongMethodToGetValue())

In this case, myLog is an interface assigned at runtime. If it is of
type NullLogger, will this still not evaluate
executeLongMethodToGetValue?

Thanks!
 
Now, my question is, the ILogger instance is assigned at runtime. So,
if I assign the NullLogger at runtime, which has [Conditional("DEBUG")]
will it still for sure not evaluate the parameters passed to the Log
method if it is of type NullLogger?

No it will evaluate the parameters. The ConditionalAttribute is a
compile-time feature.

Your code shouldn't even compile. Conditional method are not allowed
to implement interface members.


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top