EDITED: Reconstructed the sample code to include a more relevant set of objects.
I have an interesting situation that I’m having trouble finding a solution for. I have an abstract class with an abstract function that uses generics (see example code below). In an inheriting class, I’m trying to overload the function, but I’m getting
Error CS0030: Cannot convert type ‘Sample.Thingy’ to ‘T’ (CS0030)
Naturally, this isn’t my real code, but this code produces the same result as what I’m getting. If I try casting the return value to (T), I get a similar error. If I try adding where T : BaseThingy or where T : Thingy, then I get
Error CS0460: ‘Sample.Container.GetThingy(Guid)’: Cannot specify constraints for overrides and explicit interface implementation methods (CS0460)
namespace Sample {
// The abstract base class for thingies
public abstract class BaseThingy {
private Guid m_ID;
private String m_Name;
public BaseThingy( ) {
m_ID = Guid.NewGuid( );
}
public BaseThingy( Guid id ) {
m_ID = id;
}
public Guid ID {
get {
return m_ID;
}
}
public String Name {
get {
return m_Name;
}
set {
m_Name = value;
}
}
}
// The abstract base class for containers
public abstract class BaseContainer {
public abstract T GetThingy<T>(Guid id) where T : BaseThingy;
}
// Inherits from BaseThingy
public class RedThingy : BaseThingy {
private DateTime m_Created;
public RedThingy( ) : base( ) {
m_Created = DateTime.Now;
}
public RedThingy( Guid id ) : base( id ) {
m_Created = DateTime.Now;
}
public DateTime Created {
get {
return m_Created;
}
}
}
// Inherits from BaseThingy
public class BlueThingy : BaseThingy {
public BlueThingy( ) : base( ) {
}
public BlueThingy( Guid id ) : base( id ) {
}
}
// Inherits from BaseContainer
public class Container : BaseContainer {
private System.Collections.Generic.Dictionary<Guid, RedThingy> m_RedThingies;
private System.Collections.Generic.Dictionary<Guid, BlueThingy> m_BlueThingies;
public Container( ) {
m_Thingies = new System.Collections.Generic.Dictionary<Guid, BaseThingy>();
}
public override T GetThingy<T>( Guid id ) where T : BaseThingy {
if( typeof( T ) == typeof( RedThingy ) {
if( m_RedThingies.ContainsKey( id ) ) {
return m_RedThingies[ id ];
} else {
return null;
}
} else if( typeof( T ) == typeof( BlueThingy ) ) {
if( m_BlueThingies.ContainsKey( id ) ) {
return m_BlueThingies[ id ];
} else {
return null;
}
} else {
return null;
}
}
public void AddThing( RedThingy item ) {
if( item != null && !m_RedThingies.ContainsKey( item.ID ) ) {
m_RedThingies.Add( item.ID, item );
}
}
public void AddThing( BlueThingy item ) {
if( item != null && !m_BlueThingies.ContainsKey( item.ID ) ) {
m_BlueThingies.Add( item.ID, item );
}
}
}
}
The answer is that the type you pass has to inherit from
BaseThingybut it doesn’t imply that you can cast aThingyto it. Let me make an example to simplify it:Bar()will expectresultto be of typeThingy2butGetItemis trying to return aThingy1.