1

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?

user2292539
  • 245
  • 1
  • 11

1 Answers1

4

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.

AlexD
  • 32,156
  • 3
  • 71
  • 65
  • +1. Your answer would be much more helpful if you provided an example. – Jim Mischel Jul 22 '14 at 00:15
  • @DavidPeden The answer you refer to does run-time checking. PO mentioned `#if DEBUG`, so I guess compile-time checking is quite OK here. – AlexD Jul 22 '14 at 00:45
  • @AlexD The final question "Is there some way other then to have ugly defines around every single log?" clearly demonstrates a desire to avoid #defs. Most mature logging frameworks support lambda expressions which do not require an explicit run-time check. – David Peden Jul 22 '14 at 04:20