Lars Fosdal 1792 Posted May 9, 2019 I am quite fond of class variables of the Class of TSomeClass type. I use these for polymorph creation of class instance variables, typically handlers of some sort, but C# does AFAIK not have a similar construct, i.e. type as a variable. What are the best practice alternatives to using class variables? Am I limited to case / if then else factories or is there something more elegant around? Share this post Link to post
Stefan Glienke 2002 Posted May 9, 2019 (edited) https://refactoring.guru/replace-constructor-with-factory-method However I would go a step further and use delegates where you stick that implementation into. Example: You have Cat and Dog class that both derive from Animal - now because Func<T> is covariant you can write this: Func<Animal> makeAnimal = () => new Dog(); Or you can make some function that creates these Func<T> for you - then you can write: var makeCat = MakeFactory<Cat>(); // this is basically like the place in Delphi code where you would assign the TCat class to a TAnimalClass variable makeAnimal = makeCat; // again - covariant - a function returning a cat can be assigned to a func returning an animal var cat = makeAnimal(); // cat will be of type Animal though because that is the return type of makeAnimal - but that is the same for Delphi meta classes Or just use DI 😉 Edited May 9, 2019 by Stefan Glienke 1 Share this post Link to post