C# Question about Inheritance with Generic classes

Started by
2 comments, last by Postie 11 years, 9 months ago
~Pseudo Code:

public class Manager
{
List<GenericBase<IDisposeable>> list;
public void Add(GenericBase<IDisposable> obj)
{
list.add(obj);
}
}
public class GenericBase<T> where T : IDisposable
{

}
public class Resource : IDisposable
{

}
public class Inherited : GenericBase<Resource>
{

}


So what if I want to add an Inherited object to the list inside manager? I would think that the conversion to a GenericBase<IDisposeable> would be trivial considering that Resource inherits from IDisposeable and Inherited inherits from GenericBase. However, I get an error saying this conversion is not possible. Now I know that I can write a conversion operator inside Inherited to fix this but I feel like it is annoying and redundant to do this every time I create a new class inheriting from the GenericBase class. Is there anyway to get around this?
J.W.
Advertisement
So, your GenericBase class is only set up with a constraint on T. The class itself doesn't say it implements IDisposable.

The quick fix would be:


public class GenericBase<T> : IDisposable where T : IDisposable
Tried it in the editor and it still won't convert. Giving me the same error
J.W.
I think the type of your generic list is too complex for it to resolve, so you could try simplifying it by having a common base class like so:


public class Manager
{
List<GenericBase> list = new List<GenericBase>();
public void Add(GenericBase obj)
{
list.Add(obj);
}
}
public abstract class GenericBase
{
}

public class GenericBase<T> : GenericBase where T : IDisposable
{
}
public class Resource : IDisposable
{
public void Dispose()
{
}
}
public class Inherited : GenericBase<Resource>
{
}


That compiles for me, not sure if it works how you expect it to though. If you don't like the fact that the GenericBase class has nothing in it, you could always change it into an interface.
[size="2"]Currently working on an open world survival RPG - For info check out my Development blog:[size="2"] ByteWrangler

This topic is closed to new replies.

Advertisement