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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With