Sign in to follow this  
jdub

C# Question about Inheritance with Generic classes

Recommended Posts

jdub    459
~Pseudo Code:
[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>
{

}
[/CODE]

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?

Share this post


Link to post
Share on other sites
Nypyren    12074
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:

[code]
public class GenericBase<T> : IDisposable where T : IDisposable
[/code]

Share this post


Link to post
Share on other sites
Postie    1559
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:

[CODE]
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>
{
}
[/CODE]

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this