0

I tried to create same base generic variable and assign to it every generic object that have param wich inheritance same interface , but I got an error "Cannot implicitly convert type". Can some help me understand this ?

public interface ISomthink
{

}
public class Somethink: ISomthink
{

}
public class Somethink2: ISomthink
{

}
public class MyGeneric<T> where T:ISomthink
{

}
public class Program
{
    public static void Main(string[] args)
    {
        ISomthink s1 = null;
        s1=new Somethink();
        s1 = new Somethink2();

        MyGeneric<ISomthink> sg = null;
        sg=new MyGeneric<Somethink>();//Error Cannot implicitly convert type
        sg = new MyGeneric<Somethink2>();//Error Cannot implicitly convert type

    }
}
volfk
  • 99
  • 9
  • 3
    C# doesn't work that way. You can only assign `MyGeneric` instances to `sg`, or an instance of a type that *inherits* from `MyGeneric`. Even though `Somethink` implements `ISomthink`, `MyGeneric` does *not* **inherit** from `MyGeneric`. – Lasse V. Karlsen May 04 '21 at 21:47
  • Take a look at [variance](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/), specifically the [out keyword](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-generic-modifier) may be of interest to you. – Anton Curmanschii May 04 '21 at 21:48
  • best bet is to add ```public interface IMyGeneric where T : ISomthink { }``` and ```public class MyGeneric : IMyGeneric where T : ISomthink { }``` then do ```IMyGeneric sg = null;``` – Keith Nicholas May 04 '21 at 22:09

0 Answers0