Rajeshwaran S P
Rajeshwaran S P

Reputation: 582

Conditional Compiling - Phasing out Part of code in C#

I'm working on a project, where I need a set of classes to be designed and used for one phase of the project.

In the subsequent phase, we will not be needing the set of classes and methods. These set of classes and methods will be used throughout the application and so if I add them as any other classes, I would need to manually remove them once they are not required.

Is there a way in C#, so that I can set an attribute on the class or places where the class is instantiated, to avoid that instantiation and method calls based on the value of the attribute.

Something like, setting

[Phase = 2]
BridgingComponent bridgeComponent = new BridgeComponent();

Any help appreciated on this front.

Upvotes: 4

Views: 784

Answers (5)

serhio
serhio

Reputation: 28586

When the C# compiler encounters an #if directive, followed eventually by an #endif directive, it will compile the code between the directives only if the specified symbol is defined.

#define FLAG_1
...
#if FLAG_1
    [Phase = 2]
    BridgingComponent bridgeComponent = new BridgeComponent();
#else
    [Phase = 2]
    BridgingComponent bridgeComponent;
#endif

Upvotes: 3

Paolo Tedesco
Paolo Tedesco

Reputation: 57172

About methods, you can use the Conditional attribute:

// Comment this line to exclude method with Conditional attribute
#define PHASE_1

using System;
using System.Diagnostics;
class Program {

    [Conditional("PHASE_1")]
    public static void DoSomething(string s) {
        Console.WriteLine(s);
    }

    public static void Main() {
        DoSomething("Hello World");
    }
}

The good thing is that if the symbol is not defined, the method calls are not compiled.

Upvotes: 1

Maurits Rijk
Maurits Rijk

Reputation: 9985

You could also use a dependency injection framework like Spring.NET, NInject, etc. Another way is to use factory methods to instantiate your classes. You will then have a factory class for Phase1, for Phase2, etc. In the latter case you have run-time selection instead of compile time.

Upvotes: 1

Sky Sanders
Sky Sanders

Reputation: 37074

Set a compilation flag in Properties>build e.g. PHASE1

and in the code

#if PHASE1
  public class xxxx
#endif

Upvotes: 1

Blair Conrad
Blair Conrad

Reputation: 241714

Sounds like you're asking for #if.

#if Phase2
BridgingComponent bridgeComponent = new BridgeComponent();
#endif

And then use a /define Phase2 on the compile line when you want BridgingComponent included in the build, and don't when you don't.

Upvotes: 2

Related Questions