Jump to content
Registration disabled at the moment Read more... ×
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

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
Sign in to follow this  

×