1
public class P { }
public class B : P { }
public class A : P { }

public interface Interface<T> where T : P { }
public class IA : Interface<A> { }
public class IB : Interface<B> { }

public class Test
{
    public void WhatTheFuck()
    {
        Interface<P> p;
        p = new IA();// cast error here
        p = new IB();// cast error here
        //... somthing about interface<p>
    }
}

Get this error :

Severity Code Description Project File Line Suppression State Error CS0266 Cannot implicitly convert type 'AssUploaderSystem.IA' to 'AssUploaderSystem.Interface'

I want to make a generic solution because class A & B is also implemented class P.

So I want to write it only once, but I can't cast to some class . How can I do ?

3
  • 2
    define your interface Interface<out T> Commented Jan 2, 2020 at 9:36
  • 3
    Does this answer your question? Interface using generics "Cannot implicitly convert type" Commented Jan 2, 2020 at 9:55
  • @PavelAnikhouski yes. this answed my quesion. Commented Jan 2, 2020 at 9:58

1 Answer 1

5

You need to understand covariance-contravariance and variance-in-generic-interfaces

You can declare generic type parameters in interfaces as covariant or contravariant. Covariance allows interface methods to have more derived return types than that defined by the generic type parameters. Contravariance allows interface methods to have argument types that are less derived than that specified by the generic parameters. A generic interface that has covariant or contravariant generic type parameters is called variant.

As pointed out you can make it work using the following:

public class P { }
public class B : P { }
public class A : P { }

public interface Interface<out T> where T : P { }
public class IA : Interface<A> { }
public class IB : Interface<B> { }

public class Test
{
    public void WhatTheFuck()
    {
        Interface<P> p;
        p = new IA();// cast error here
        p = new IB();// cast error here
        //... somthing about interface<p>
    }

You can declare a generic type parameter covariant by using the out keyword. The covariant type must satisfy the following conditions:

The type is used only as a return type of interface methods and not used as a type of method arguments.

The type is not used as a generic constraint for the interface methods. This is illustrated in the following code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.