34

I have a Portable Class Library with a class PCLDebug:

public static class PCLDebug {
    public static Action<string> LogLine { get; set; }
}

What I want to do is set things up once in the outer project, then be able to call LogLine within the PCL to print stuff to the VS Output window. Here is my attempt:

MyPCL.PCLDebug.LogLine = System.Diagnostics.Debug.WriteLine;

The problem here is that the compiler complains, because System.Diagnostics.Debug.WriteLine has a conditional attribute of Debug:

Cannot create delegate with 'System.Diagnostics.Debug.WriteLine(string)' because it has a Conditional attribute

I am actually fine with it if the LogLine call only works in the debugging environment. But how do I keep the compiler happy?

0

2 Answers 2

58

You could try wrapping it in a lambda function:

MyPCL.PCLDebug.LogLine = s => { System.Diagnostics.Debug.WriteLine( s ); };
2
  • Why does this work but it doesn't work assigning directly? Mar 11, 2016 at 18:06
  • 7
    @reggaeguitar Because ConditionalAttribute causes the compiler to omit calls to the function, but direct assignment isn't a call, it's actually delegate construction, so it can't be omitted. The lambda works because it creates an anonymous function that either does nothing or calls the conditional function. In either case the delegate is definitely assigned.
    – Kyle
    Mar 11, 2016 at 19:32
6

you can use this alternative notation too:

    MyPCL.PCLDebug.LogLine = delegate(string text) { System.Diagnostics.Debug.WriteLine(text); };

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.