1

Is it possible to do something like:

using MyCustomDto = (flag == "library1") ? MyLibrary1.Dtos.MyDto1 : MyLibrary2.Dtos.MyDto2;

I can't figure out the right syntax for this. So depending on a flag in an appsettings.config, I want to load a Dto from a specific library, they have different namespaces as you can see, this would be part of the using directives block where commonly you see statements like:

using System.Collections.Generic;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Sami
  • 393
  • 8
  • 22
  • 2
    What you're describing is a compile-time change, but you want to do it at runtime. This is not possible. – ProgrammingLlama Sep 23 '19 at 06:54
  • 1
    You can't. You only can use , preprocessor directive #if: https://learn.microsoft.com/dotnet/csharp/language-reference/preprocessor-directives/ –  Sep 23 '19 at 06:55
  • Have you considered [Dependency Injection](https://stackoverflow.com/questions/130794) which can cater for different runtime requirements? – Dave Anderson Sep 23 '19 at 06:58
  • 1
    I've edited the title and body of the question to use the correct terminology, btw. `using` *statements* are things like: `using (var stream = File.OpenRead("..."))` whereas `using` *directives* are things like `using System;`. I hope you don't mind the edit - I didn't want to propagate the slight confusion for future readers. – Jon Skeet Sep 23 '19 at 06:59

1 Answers1

8

No. using directives are effective at compile-time, not execution-time.

You could have different compile-time configurations, with different compiler symbols defined, then use:

#if LIBRARY1
using MyLibrary1.Dtos.MyDto1;
#else
using MyLibrary2.Dtos.MyDto1;
#endif

But that would then be a fully compile-time check, and couldn't be modified using appsettings.

To be truly dynamic, you'd want a common type used in both scenarios, potentially with library-specific subclasses chosen at execution time. It's hard to give a concrete example without knowing more about what you're trying to achieve, but it's not a matter of a different using directive. The types in the code would always mean the same thing, they may just be instantiated differently, using different derived classes.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194