3

I am coding a MVC 5 internet application and I have a question in regards to using an interface with Lazy<T> initialization.

Here is the class definition in question:

public class WebAPITokenService1_0 : IWebApiTokenService

Here is my code that works with out using the interface in the declaration:

Declaration:

Lazy<WebAPITokenService1_0> webAPITokenService1_0;

Initialization:

webAPITokenService1_0 = new Lazy<WebAPITokenService1_0>();

Here is the same code, but with using an interface:

Declaration:

Lazy<IWebApiTokenService> webAPITokenService1_0;

Initialization:

webAPITokenService1_0 = new Lazy<WebAPITokenService1_0>();

Here is the error when using the interface in the declaration:

> Cannot implicitly convert type
> 'System.Lazy<CanFindLocation.Services.AndroidWebAPI._1_0.WebAPITokenService1_0>'
> to
> 'System.Lazy<CanFindLocation.Interfaces.WebService.IWebApiTokenService>'  E:\CanFindLocation\MVC\CanFindLocation\CanFindLocation\Controllers\AndroidWebAPI\1_0\WebService1_0Controller.cs

I have had a look at the Lazy Initialization, but cannot see any information about the above situation.

Can I use an interface with Lazy<T> initialization, and if so, what is incorrect with my above code?

2
  • 2
    Lazy<IWebApiTokenService> webAPITokenService1_0=new Lazy<IWebApiTokenService>(() => new WebAPITokenService1_0()); May 21, 2015 at 3:59
  • Thank you. I will accept this is answer if you would like to post an answer.
    – Simon
    May 21, 2015 at 6:46

2 Answers 2

4

Lazy<T> does not support covariance, so you must use exactly the same type in the declaration and initialization.

2

.NET supports generic variance only for interfaces and delegates, and Lazy<T> is a class. So you can not assign Lazy<Derived> instance to Lazy<Base> variable

However, you can create a Lazy<Base> instance that contains Derived instance as its Value property by using the Lazy<T> constructor that accepts a factory delegate as an argument:

Lazy<Base> lazy1 = new Lazy<Base>(() => new Derived(args1));
Lazy<Base> lazy2 = new Lazy<Base>(() => GetDerived(args2));
1
  • Good answer. I was having trouble understanding what OP was trying to accomplish.
    – BJ Myers
    May 21, 2015 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.