Roslyn: Implement shortcut of #if

Created on 27 Aug 2016  路  7Comments  路  Source: dotnet/roslyn

I have a idea about compiler.
Usually when I writing an app I put lot of log same as below:


#if DEBUG
            Console.WriteLine("Init Redis Provider")
#endif
            Provider = new RedisProvider();

#if DEBUG
            Console.WriteLine("Init Kernel");
#endif
            EFDataContext.RegisterEFDataService(Reflection.Kernel);

#if DEBUG
            Console.WriteLine("Start Web Server");
#endif
            WebServer.LocalWebApi.Start();

For make it easy I have a idea and I describe it by example at below:


#DEBUG Console.WriteLine("Init Redis Provider")
Provider = new RedisProvider();

//OR
#>DEBUG Console.WriteLine("Init Kernel"); 
EFDataContext.RegisterEFDataService(Reflection.Kernel);

//OR
#?DEBUG Console.WriteLine("Start Web Server");
WebServer.LocalWebApi.Start();

Area-Language Design Question Resolution-Answered

Most helpful comment

@OmidID

But anyway in same case you consumption time to execute Debug.WriteLine() for nothing in release production.

No you don't. The compiler will omit the calls to the decorated method entirely if the specified preprocessor directive is not set.

All 7 comments

Have you considered using a method with [ConditionalAttribute("DEBUG")] instead? That method could be either Debug.WriteLine() (which needs setup in the form of Debug.Listeners.Add(new ConsoleTraceListener()); to write to the console), or a custom method that wraps Console.WriteLine().

@svick Yes. I know that. it was an example. But anyway in same case you consumption time to execute Debug.WriteLine() for nothing in release production.

@OmidID

But anyway in same case you consumption time to execute Debug.WriteLine() for nothing in release production.

No you don't. The compiler will omit the calls to the decorated method entirely if the specified preprocessor directive is not set.

@HaloFour so you mean if I compile the code with "Debug.WriteLine()" for Release then in decompile il code it shouldn't be exists right?

@OmidID That is correct.

Yep. I've never liked that behavior for Debug.WriteLine(), it is too easy to introduce unnoticed bugs by putting logic inside the expression serving your Debug.WriteLine(...) call. I had a bug go into production because of this, even though it "worked for me"... and it can be a nasty thing to hunt down.

Yeh. as @svick said I start to use [ConditionalAttribute("DEBUG")] in my codes. And now looks working without any problem in release. take look here:
https://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute(v=vs.110).aspx
without any modification just call your method and you can remove them easily by this attribute.
C# is the best ever

Was this page helpful?
0 / 5 - 0 ratings