This question already has an answer here:
Casting Deriving Class as Base Class
I have a base abstract class which is generic and inherits from IComparable which is defined like below
public abstract class BaseClass<T> where T : IComparable
{
protected readonly T Data;
protected BaseClass(T data)
{
Data = data;
}
public abstract T Get();
}
Then I have defined a classe which inherits from this base class and has a specific generic type and is defined like below:
public class Name : BaseClass<String>
{
public Name(string data) : base(data)
{
}
public override string Get()
{
throw new NotImplementedException();
}
}
As generic type is string and string inherits from IComparable, I expect to be able to define new Name object with string value as generic type, but I get casting error for defining Name object like this:
BaseClass<IComparable> obj;
obj = new Name("behro0z");
and the error is
Error CS0029 Cannot implicitly convert type
ConsoleApplication1.Name
toConsoleApplication1.BaseClass<System.IComparable>
ConsoleApplication1
You're declaring a variable of type
BaseClass<T>
, and substituteT
withIComparable
.That's valid, but that's not what your
Name
class is. That one derives fromBaseClass<string>
, notBaseClass<IComparable>
, even thoughstring
implementsIComparable
.You can either declare your variable
obj
to be of typeBaseClass<string>
, or the more derived type,Name
.Read up on covariance, C# Generics Inheritance Problem.