Search code examples
c#conditional-attribute

Is it possible to use the conditional attribute to create similliar debugger and run-time method?


is it possible to create 2 methods that have the same method-name, passed in values and returns using the conditional attribute and some anti conditional for example

[Conditional("Debug")]
    private string StringGenerator()
    {
        Guid g = Guid.NewGuid();
        string guidString = Convert.ToBase64String(g.ToByteArray());
        guidString = guidString.Replace("=", "");
        guidString = guidString.Replace("+", "");
        return guidString;
    }


    [!Conditional("Debug")]// I know using '!' doesn't really work
    private string StringGenerator()
    {
        Guid g = Guid.NewGuid();
        string guidString = Convert.ToBase64String(g.ToByteArray());

        return guidString;
    } 

so that you could just call a method and based on whether "Debug" is defined the compiler will choose which method?

Thanks


Solution

  • You can try using the #if DEBUG syntax like so:

    #if DEBUG
        private string StringGenerator()
        {
            Guid g = Guid.NewGuid();
            string guidString = Convert.ToBase64String(g.ToByteArray());
            guidString = guidString.Replace("=", "");
            guidString = guidString.Replace("+", "");
            return guidString;
        }
    
    #else
        private string StringGenerator()
        {
            Guid g = Guid.NewGuid();
            string guidString = Convert.ToBase64String(g.ToByteArray());
    
            return guidString;
        }
    #endif 
    

    However, there are some differences with using this. See this question for more details.