i have a problem using Covariance and Contravariance with generic interface and list of base object. Here my class scheme (Reduced and simplified):
abstract class Human : IHuman {
public string Ethnicity { get; set; }
}
interface IHuman {
string Ethnicity { get; set; }
}
class Person : Human {
public string Name { get; set; }
}
class Man : Person {
protected string Age { get; set; }
}
class Women : Person {
protected string AgeWrong { get; set; }
}
class Worker<T> : Person, IWorker<T> where T : IHuman {
public string Code {
get { return this.Name + this.Ethnicity; }
}
public Human Call(T who) {
return null;
}
}
interface IWork<out T> where T : IHuman {
string Name { get; }
}
interface IWorkBase<in T> where T : IHuman {
Human Call(T who);
}
interface IWorker<T> : IWork<T>, IWorkBase<T> where T : IHuman { /*Empty*/ }
static void Main(string[] args) {
var list = new List<Human>();
list.Add(new Man());
list.Add(new Women());
list.Add(new Worker<Man>());
list.Add(new Worker<Women>());
// Now i search by interface type
var workers = from gr in list where (gr as IWorker<IHuman> != null) select (IWorker<IHuman>)gr;
// here workers is Empty!!! :((( but if "i cast with Covariance"...like:
var workersCov = from gr in list where (gr as IWork<IHuman> != null) select (IWork<IHuman>)gr;
var w = new Worker<Man>();
// Simple Test:
Console.WriteLine(w is IWorker<Human>);
Console.WriteLine(w is IWork<Human>);
}
My question is why my cast works only with Covariance ? I have added simple test without LINQ.
Thanks.