How to use the Covariance(out keyword)?I have no idea.
I know out keyword in Interface mean Covariance that allow you use a more derived type than that specified by the generic parameter. So i set generic to object and return type to string.Because string is subclass of object. But i tried and it not working.
public interface IMyInterface<out T>
{
public T Foo();
}
public class CovarianceTest : IMyInterface<object>
{
public string Foo()
{
return "abc";
}
}
CodePudding user response:
Covariance that allow you use a more derived type than that specified by the generic parameter
That's not what it means. You still have to write methods that match the types in the interface. So you will have to do this:
public class CovarianceTest : IMyInterface<string>
{
public string Foo()
{
return "abc";
}
}
What covariance allow you to do is assign the class instance to a variable typed as a less specific interface, like this:
IMyInterface<object> x = new CovarianceTest();
Console.WriteLine(x.Foo());
That's because all T
s read from the interface (i.e. taken out
) are guaranteed to be instances that are type-compatible with the less specific type, i.e. all strings are also objects.
CodePudding user response:
I suspect you are trying to do the following.
public interface IMyInterface<out T>
{
public T Foo();
}
public class CovarianceTest : IMyInterface<string>
{
public string Foo()
{
return "abc";
}
}
IMyInterface<string> works = new CovarianceTest();
IMyInterface<object> alsoWorks = new CovarianceTest();
IMyInterface<int> doesNotWork = new CovarianceTest();