i have a problem that I do not understand about casting in interfaces with generic (probably because covariance and contravariance are not completly clear to me at the moment).
I have an Interface where i define a getter and setter that should accept anything in a typed way (no object as type) Eg :
public interface IDummy <T>
{
int SomeCommonMethod() ;
T Anything { get; set; }
}
Now i define some concretes implementation of interface defined before.
public class MyStrObj : IDummy <string>
{
private string _stirngVal = string.Empty ;
public int SomeCommonMethod()
{
return 0 ;
}
public string Anything
{
get { return _stirngVal ; }
set { _stirngVal = value ; }
}
}
public class MyFileObj : IDummy <File>
{
private File _file = null ;
public int SomeCommonMethod()
{
return 0 ;
}
public File Anything
{
get { return _file ; }
set { _file = value ; }
}
}
At time all works as expected, but now when try to use this two object their behaviour start becoming confusing for me.
I try to define an object that should be able to consume both previous classes (no matter which type they has in their generics, what matter is that they are IDummy).
public class Consumer
{
public static void Consume ( IDummy<object> obj )
{
//SOME CODE HERE.
}
}
Now if i try this code :
MyStrObj obj = new MyStrObj () ;
Consumer.Consume ( obj ) ;
then compiler notice to me that there are some invalid parameters over Consume method calling (obj sure), but there is not an implicit cast here?
If i try this way instead :
MyStrObj obj = new MyStrObj () ;
Consumer.Consume ( (IDummy<object>)obj ) ;
compiler seems to work as I suppose it should (at time I have not tested if the two calls are equivalent).
Thanks in advance for anyone that can help me to understand this behaviour, and sorry for my english (is not my language).
Your IDummy<T> is not covariant. That is why the implicit conversion of such does not work. If it were covariant, the conversion from more specific generic type to the more general one would work. However in your example you cannot make your interface covariant IDummy<out T>, since it has a property setter with your generic parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With