user2292539
user2292539

Reputation: 245

log statement avoid computing parameters

In c# is there a way to avoid computing expensive parameters.

Example

DebugLog(object.getName());

If I want to avoid the call to getName(say its expensive) I have to do

#if DEBUG
DebugLog(object.getName());
#endif

In other languages I can make a log macro that is a no-op if the log level is a certain way and just do

DebugLog(anything i want as it just is skipped)

Is there some way other then to have ugly defines around every single log?

Upvotes: 1

Views: 60

Answers (1)

AlexD
AlexD

Reputation: 32616

In can be done with help of conditional attributes. E.g. if you have [ConditionalAttribute("DEBUG")], and DEBUG is not defined, the entire function call, including evaluation of parameters is skipped.

This is, for instance, how Debug.Assert works.

For instance, this code

static void Main()
{
    Log(F());
}

[ConditionalAttribute("DEBUG")]
static void Log(string s)
{
    Console.WriteLine(s);
}

static string F()
{
    Console.WriteLine("foo");
    return "bar";
}

outputs

foo
bar

in Debug configuration, where DEBUG is defined, and nothing in Release configuration.

Upvotes: 4

Related Questions