Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to Conditional Compilation in C#

What is the alternative to having code with conditional compilation in C#?

I have a class that has lots of code that is based on # ifdef .. After sometime my code is unreadable.

Looking for refactoring techniques to use for better readability and maintenance of code with many #if defs

like image 337
Venki Avatar asked Sep 24 '10 12:09

Venki


2 Answers

An alternative is to use the ConditionalAttribute. The conditional attribute works in a similar way.

#define TRACE_ON
using System;
using System.Diagnostics;

public class Trace 
{
    [Conditional("TRACE_ON")]
    public static void Msg(string msg)
    {
        Console.WriteLine(msg);
    }
}  

public class ProgramClass
{
    static void Main()
    {
        Trace.Msg("Now in Main...");
        Console.WriteLine("Done.");
    }
}
like image 84
TheCodeKing Avatar answered Oct 17 '22 22:10

TheCodeKing


One thing is to use the ConditionalAttribute:

[Conditional("DEBUG")]
public void Foo()
{
    // Stuff
}

// This call will only be compiled into the code if the DEBUG symbol is defined
Foo();

It's still conditional compilation, but based on attributes rather than #ifdef, which makes it generally simpler.

Another alternative is simply to use Boolean values at execution time, instead of doing it all at compile time. If you could give us more details of what you're trying to achieve and how you're using conditional compilation, that would be useful.

like image 28
Jon Skeet Avatar answered Oct 17 '22 22:10

Jon Skeet