-
I was surprised to see that this doesn't compile: public interface IFoo<out T, TThis> where TThis : IFoo<T, TThis>
{
public static abstract TThis Create(T val);
} It results in the usual error The thing is, I can't figure out why variance applies to static members. The purpose of variance is so that an instance of Strangely enough, this is allowed: public interface IFoo<out T, TThis> where TThis : IFoo<T, TThis>
{
static TThis Create(T val) => throw new NotImplementedException();
} so it's the abstractness of the member that causes it to be checked for variance; I'm not sure I understand the significance. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
This is not related to |
Beta Was this translation helpful? Give feedback.
-
Variance does apply to static members. interface IFoo<in T, TThis> where TThis : IFoo<T, TThis>
{
static abstract TThis Create(T val);
}
class C : IFoo<object, C>
{
public static C Create(object val) => new C();
}
static class S
{
static T Create<T>(string val) where T : IFoo<string, T> => T.Create(val);
static C Create(string val) => Create<C>(val);//this compiles due to contravariance.
} |
Beta Was this translation helpful? Give feedback.
Variance does apply to static members.