Search code examples
c#inheritanceabstract-class

Conditional inheritance: base class depend on environment variable


I have two abstracts classes, 'ValidationsWithStorage' inherits 'Validations'

   public abstract class Validations {
    // methods..
   }

   public abstract class ValidationsWithStorage : Validations { 
    // ... 
    }

I also have a class:

public abstract class TestsValidations : T

T should be depend on the environment variable:

Environment.GetEnvironmentVariable("useStorage") 

If this variable is null I want that T will be Validations. Else, I want that T will be ValidationsWithStorage.

What is the best way to do it?

Thanks


Solution

  • You can do that using conditional compilation:

    public abstract class TestsValidations
    #if USESTORAGE
        : ValidationsWithStorage
    #else
        : Validations
    #endif
    {
    
    }
    

    You can set it in project configuration or by passing additional parameters to msbuild: /p:DefineConstants="USESTORAGE"

    I don't think this is good design, but it is doable.