Jump to content
  • Advertisement
Sign in to follow this  
jdub

C# Question about Inheritance with Generic classes

This topic is 2207 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

~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?

Share this post


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

Share this post


Link to post
Share on other sites
Tried it in the editor and it still won't convert. Giving me the same error

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!