I have a book that explains contravariance/covariance as follows :
- a delegate can have more specific parameter types than its method target. This is called contravariance
- the return type of a delegate can be less specific than the return type of its target method. This is called covariance
And, this is an example.
using System;
delegate void StringAction(string s);
delegate object ObjectRetriever();
class Test
{
static void Main()
{
StringAction sa = new StringAction(ActionObject);
sa("hello");
ObjectRetriever o = new ObjectRetriever(RetrieveString);
object result = o();
Console.WriteLine(result);
}
static string RetrieveString() {return "hello";}
static void ActionObject(object o)
{
Console.WriteLine(o);
}
}
I thought in order to use covariance/contravariance, one needs to use new
as is shown in the example, but I seem to get the same result with sa = ActionObject
and o = RetrieveString
. (I tested with Mono).
- Then, why the writer uses
new
to explain covariance/contravariance? - What's the theory behind the covariance/contravariance idea? Is it just a fancy name describing
object x = Everything inherit from object
? Where is this weird name come from? What's the usage for it?