0

I want to access a static class of a name that I don't know at compile time - that's not a good description so let me elaborate.

Imagine: 3 static classes that all inherit from an interface,

Now a fourth class wants to access a function in that interface but for one of the 3 classes. And I don't know which of the 3 it's going to be at compile time.

Some Research

I've looked into, and in the past, used things like Activator.CreateInstance(); to solve this problem for non-static classes, but now I'd like to do it with static classes and I'm lost.

I've also seen people storing references to the classes in a dictionary of <string, interface> and then accessing the classes by their name that way but this isn't ideal since it requires a lot of boilerplate. (I have quite a few more than 3 classes that are possibilities)

A potential solution

I could just create instances as I mentioned before but this seems wasteful which is why I've decided I want to use static classes. Perhaps this isn't as big of a problem as I thought and I should refer myself to the rules of optimisation...

Chris
  • 87
  • 2
  • 10
  • 1
    Creating instances of an object (so long as it does not have an involved constructor) is a *very* cheap operation. There's not really anything you could reasonably do that would be *cheaper* than that. Particularly if you use singletons, and thus only have that miniscule cost once. – Servy Dec 29 '21 at 22:04
  • 1
    *"3 static classes that all inherit from an interface"* - Static classes cannot implement interfaces (verbatim, that's the message for error CS0714) so that's a non-starter. – madreflection Dec 29 '21 at 22:08
  • 1
    I'm completely confused about what your use case is: how do you have static classes inheriting interfaces and what would be the purpose of them doing so? It sounds like you need something like a Dependency Injection system or something, but it's really unclear – Charlieface Dec 29 '21 at 22:24

0 Answers0