1

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.

  • 1
    If you're able to decide at compile time, maybe you could use preprocessor directives? – ProgrammingLlama Apr 29 '22 at 10:18
  • You can load assembly (dll) and create an instance of your object something like this: https://stackoverflow.com/a/1803881/754438 – Renatas M. Apr 29 '22 at 12:02
  • have you thought about doing this with Dependency injection? then just injecting the service you need based on a check. That way you just inherit from the same interface. Just a thought. – Netferret Apr 29 '22 at 13:10

1 Answers1

0

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();
Fabiano
  • 5,124
  • 6
  • 42
  • 69