I have a factory method that returns the correct sub class depending on three enum values.
One way to do is, would be to use switches in switches in switches. Obviously, I don’t like that option very much.
I thought that another option would be to use attributes in C#. Every sub class would have an attribute with that 3 enum values and in the factory I would only have to get the class that has the same enum values corresponding to the enum values i have in the factory.
However, I am quite new to attributes and I did not find any suitable solution in the web. If anyone, could just give me some hints or some lines of code, I really would appreciate that!
First of all, declare your attribute and add it to your classes.
Then, you can use this code to create a dictionary with your enums and types, and dynamically create a type.
As you can probably notice, calling
Activator.CreateInstanceis not performant. Therefore, if you want to improve the performance a little bit, you can change the dictionary toDictionary<MyEnum,Func<object>>and instead of adding types as values you would add functions wrapping the constructor of each of your classes and returning them as objects.EDIT: I’m adding a
ConstructorFactoryclass, adapted from this page.You can use it as an alternative to
Activator.CreateInstance, it provides greater performance if the result is cached.