'Can you specify use site variance in C#?
Does C# have the equivalent of Java's wildcards? I know C# has declaration site variance. However, I wonder if the language offers an option to specify use-site variance. Here is an example of what I'm looking for:
class Parent {}
class Child : Parent {}
class Grandchild : Child {}
interface IProducer<out T>
{
T produces();
}
interface IConsumer<in T>
{
void consumes(T p);
}
class Collection<T> : IProducer<T>, IConsumer<T>
where T:new()
{
private readonly T _v;
public Collection()
{
_v = new T();
}
public T produces()
{
return _v;
}
public void consumes(T p)
{
//
}
public static void Main(string[] args)
{
Collection<Child> coll = new Collection<Child>(); // Invariance
IProducer<Parent> producer = coll; // Producer using declaration site variance and segregating by interface
IConsumer<Grandchild> consumer = coll; // Consumer using declaration site variance and segregating by interface
// Equivalent of Collection<? extends Parent> producer = coll; ?
// Equivalent of Collection<? super Grandchild> producer = coll; ?
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
