views:

148

answers:

5

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.

+3  A: 

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
serhio
can this DEBUG be anything like a value in App.config?
Rajeshwaran S P
you can declare your own precompiler variables, but afak not dynamically. `#define MY_FLAG`
serhio
+1  A: 

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.

Blair Conrad
I think #if is what I need. Thanks Blair
Rajeshwaran S P
+1  A: 

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

and in the code

#if PHASE1
  public class xxxx
#endif
Sky Sanders
A: 

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.

Maurits Rijk
+1  A: 

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.

Paolo Tedesco
for the methods, i can use this. Thanks!
Rajeshwaran S P