Search code examples
c#attributesdelegatesportable-class-library

Create a delegate when there is a conditional attribute


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?


Solution

  • You could try wrapping it in a lambda function:

    MyPCL.PCLDebug.LogLine = s => { System.Diagnostics.Debug.WriteLine( s ); };