looking at this code
delegate void StringAction (string s);
class Test
{
static void Main()
{
StringAction sa = new StringAction (ActOnObject);
sa ("hello");
}
static void ActOnObject (object o)
{
Console.WriteLine (o); // hello
}
}
Is this code is working due to Contravariance ? ( MoreDeriverdRef <== LessDerivedRef )
or because
(unrelated to contravariance) – In c# I can execute a method like ActOnObject (object o) with ActOnObject ("lalala")
This code works because, as Eric Lippert says in this article:
The above is only true for reference types, but both
stringandobjectare reference types, so the requirements are satisfied.This kind of variance has been supported since C# 2.0, you do not need the additional support introduced in version 4 to rely on it.