Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Covariant use of generic Lazy class in C#

Assuming that this applies:

public class Cat : Animal { }

and assuming that I have a method:

public void Feed(Animal animal) { ... }

And I can call it this way:

var animal = new Cat();
Feed(animal);

How can I get this working when Feed is refactored to only support Lazy<Animal> as parameter? I'd like to pass in my var lazyAnimal = new Lazy<Cat>(); somehow.

This obviously doesnt work:

var lazyAnimal = new Lazy<Cat>();
Feed(lazyAnimal);
like image 273
thmshd Avatar asked Nov 30 '22 19:11

thmshd


1 Answers

You can't, basically - not directly, anyway. Lazy<T> is a class, so doesn't suppose generic variance.

You could create your own ILazy<out T> interface, implement it using Lazy<T>, and then make Feed take ILazy<Animal> instead. The implementation would be trivial.

Alternatively, you could make Feed generic:

public void Feed<T>(Lazy<T> animal) where T : Animal

Or Servy's suggestion of taking Func<Animal> would work too, and you could call it using a lambda expression for the Lazy<T>:

Feed(() => lazyAnimal.Value);
like image 130
Jon Skeet Avatar answered Dec 05 '22 01:12

Jon Skeet