I am just starting to get to grips with generics and am (ab)using them to refactor a fairly complex section of my code (I've only been using c# for a little while but am fairly experienced in other languages).
I have an inheritance structure where my classes extend a base class. In the base class I have most of the functionality implemented. But I want to be able to associate these children classes with instances of their siblings.
Here is a simplification of some of the relevant code:
class ParentClass<T>
where T : ParentClass<T>, new()
{
public static T Create()
{
return new T();
}
private object joinedItem;
public void Join<TJoinee>(TJoinee item)
where TJoinee : ParentClass<TJoinee>, new()
{
joinedItem = item;
}
}
class ChildOne : ParentClass<ChildOne>
{
}
class ChildTwo : ParentClass<ChildTwo>
{
}
With this code in place I can do something like:
var a = ChildOne.Create();
a.Join(new ChildTwo());
The problem is that I needed to type joinedItem
as object when really I want to type it as ParentClass<Something>
. Is it possible to prescribe a more specific type to joinedItem
? Or am I just horribly abusing the language and should be taking a completely different approach?