MasterClass is the base class, Attachvariable inherits from this. Table stores MasterClass objects.
public class Table
{
private Dictionary<int, MasterClass> map = new Dictionary<int, MasterClass>();
public bool isInMemory(int id)
{
if (map.ContainsKey(id))
return true;
return false;
}
public void doStuffAndAdd(MasterClass theclass)
{
theclass.setSomething("lalala");
theclass.doSomething();
map[theclass.id] = theclass;
}
public MasterClass getIt(int id)
{
return map[id];
}
}
So now this happens:
Table table = new Table();
if (!table.isInMemory(22))
{
Attachvariable attachtest = new Attachvariable(22);
table.doStuffAndAdd(attachtest);
Console.WriteLine(attachtest.get_position()); //Get_position is a function in Attachvariable
}
else
{
Attachvariable attachtest = table.getIt(22); //Error: Can't convert MasterClass to Attachvariable
Console.WriteLine(attachtest.get_position());
}
Is there any way to make Table work with any class that inherits from MasterClass, without knowing about that class’ existance up front, so that I can still use doStuffAndAdd(MasterClass theclass) and also use Attachvariable as a return type for getIt().
I can’t use Table<T> because then doStuffAndAdd can’t add a MasterClass object to the Dictionary. There’s no way to check if T inherits from MasterClass so that’s not suprising… how do I make this work?
public class Table<T>
{
private Dictionary<int, T> map = new Dictionary<int, T>();
public bool isInMemory(int id)
{
if (map.ContainsKey(id))
return true;
return false;
}
public void doStuffAndAdd(MasterClass theclass)
{
theclass.setSomething("lalala");
theclass.doSomething();
map[theclass.id] = theclass; //Error: can't convert MasterClass to T
}
public T getIt(int id)
{
return map[id];
}
}
I believe this:
has to be
You can check if a class inherits another by doing: