I have a class like this:
public sealed class Repository<T> : IRepository<T>
where T : RepositoryEntryBase, IRepositoryEntry, new()
{
/*Insert Stuff Here*/
}
I am trying to instantiate this class like so:
Repository<dynamic> v = new Repository<dynamic>();
and I'm getting an error like this:
The type 'dynamic' cannot be used as type parameter 'T' in the generic type or method 'ServiceLibraries.Repositories.Repository'. There is no implicit reference conversion from 'dynamic' to 'Data.IRepositoryEntry'.
The MSDN documentation says the following, though:
At compile time, an element that is typed as dynamic is assumed to support any operation.
Is there something I'm missing? Any thoughts on how to resolve this?
Consider non-dynamic code within Repository<T>
. It could have:
IRepositoryEntry entry = new T();
That's perfectly valid code - but isn't going to work with T=dynamic
.
You can perform any operation on a value of type dynamic
, but that doesn't mean you can use dynamic
in every situation - and generics are precisely an example of where that just doesn't work.
It's important that the "dynamic-ness" only affects the code which knows (at compile-time) that it's using dynamic
... so that doesn't include the Repository<T>
code here, for example.
See more on this question at Stackoverflow