I am learning "contravariant generic delegate".
My understanding is:
The "in" keyword specifies that the type parameter is contravariant.
This allows for implicit conversion of delegate types.If there is no "in" keyword, we don't know if the type parameter is contravariant.
Then implicit conversion of delegate types are not allowed.
Here is my code:
public class Test
{
//public delegate bool FuncDelegate<T>(T t);
public delegate bool FuncDelegate<in T>(T t);
public class BaseClass
{
public int x;
}
public class DerivedClass: BaseClass
{
public int y;
}
static bool BaseFunc(BaseClass bc)
{
if (bc.x > 1)
return false;
else
return true;
}
static bool DerivedFunc(DerivedClass dc)
{
if (dc.y > 1)
return false;
else
return true;
}
public static void Main()
{
FuncDelegate<DerivedClass> genericDerivedFunc = DerivedFunc;
FuncDelegate<BaseClass> genericBaseFunc = BaseFunc;
genericDerivedFunc = genericBaseFunc;
FuncDelegate<DerivedClass> genericDerivedFunc2 = BaseFunc;
}
}
My question
/*
This line is valid when declared as: public delegate bool FuncDelegate<in T>(T t);
This line is invalid when declared as: public delegate bool FuncDelegate<T>(T t);
*/
genericDerivedFunc = genericBaseFunc;
This line agrees with my undertanding.
/*
This line is always valid.
*/
FuncDelegate<DerivedClass> genericDerivedFunc2 = BaseFunc;
I don't understand this line:
"bool BaseFunc(BaseClass bc)" can implicitly converts to bool "FuncDelegate<DerivedClass>(DerivedClass t)".
I think it must have the "in" keyword to specifies contravariant.
But the conversion can be done without the "in" keyword.