Jump to content
Sign in to follow this  
Lars Fosdal

C# offtopic: Class of TSomeClass - Alternatives?

Recommended Posts

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

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 by Stefan Glienke
  • Like 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×