'Can I use different namespace as variable depending on the configuration?

For example, I have two namespaces, provided by other dlls. and cannot be modified.

namespace A_Build 
{
   public class D {}
   public class E {}
}
namespace A_Test 
{
   public class D {}
   public class E {}
}

There is also a method that need to be designed to returns an object dynamically.

public dynamic get_D()
{
    string stage = ConfigurationManager.AppSettings["stage"];

    if(stage = "Build")
    {
        return new A_Build.D();
    }
    if(stage = "Test")
    {
        return new A_Test.D();
    }
    return object;
}

Since there will be a lot of constructor A_{stage}.D() I want the namespace to act like a variable to make code more cleaner.

For example

if(stage = "Build")
{
    using A = A_Build;
}
if(stage = "Test")
{
    using A = A_Test;
}    
public dynamic get_D()
{
    return new A.D();
}

How could I fix the syntax to achieved my desired result.



Solution 1:[1]

You could try it with a delegate. Something like this:

Func<dynamic> newObject;
if (stage == "Build")
{
    newObject = () => new A_Build.D();
}
if (stage == "Test")
{
    newObject = () => new A_Test.D();
}
return newObject();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fabiano