Jump to content

  • Log In with Google      Sign In   
  • Create Account


C# Question about Inheritance with Generic classes


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 jdub   Members   -  Reputation: 411

Like
0Likes
Like

Posted 04 July 2012 - 05:07 PM

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

Sponsor:

#2 Nypyren   Crossbones+   -  Reputation: 3415

Like
1Likes
Like

Posted 04 July 2012 - 07:31 PM

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


#3 jdub   Members   -  Reputation: 411

Like
0Likes
Like

Posted 04 July 2012 - 09:01 PM

Tried it in the editor and it still won't convert. Giving me the same error
J.W.

#4 Postie   Members   -  Reputation: 746

Like
0Likes
Like

Posted 05 July 2012 - 01:43 AM

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.
Currently working on an open world survival RPG - For info check out my Development blog: ByteWrangler




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS