Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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

and in the code

#if PHASE1
  public class xxxx
#endif

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top