Search code examples
c#hangfire.net-4.7.2

Error CS0765 When Creating Expressions without Define DEBUG Constant set in the build settings for a configuration in VS 2019 C#


In my .Net 4.7.2 MVC5 web application I am trying to declare an expression using the following code:

Expression<Action> expresssion = () => Debug.WriteLine("Easy!");

this line does not compile and gives the following error ONLY when the current configuration does not have the "Define DEBUG Constant" value checked:

Error CS0765 Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees

when I go to the Project's properties page and check the Define DEBUG Constant, not only does the error go away with Intellisense but also build and works as expected.

Is this value supposed to be required for Expressions to work?

Background Information:

  • I am able to check and uncheck the DEBUG Constant value and the error disappears/appears
  • I'm using VS 2019 enterprise.

Solution

  • The Debug.WriteLine method is attributed with the Conditional attribute.

    [Conditional("DEBUG")]
    public static void WriteLine(string? message)
    

    The documentation gives a clue...

    //
    // Summary:
    //     Indicates to compilers that a method call or attribute should be ignored unless
    //     a specified conditional compilation symbol is defined.
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
    public sealed class ConditionalAttribute : Attribute
    

    If the DEBUG symbol is not defined, the WriteLine(string) method will be "ignored" by the compiler, and thus the expression is "incomplete", or as if it was never assigned properly, and thus the error.

    To solve the problem, put the Debug.WriteLine statement in another named function, and use that function in the expression instead.

    Expression<Action> expresssion = () => WriteDebug("Easy!");
    
    ....
    
    private static void WriteDebug(string str)
    {
        Debug.WriteLine(str);
    }