I have the following example relationship:
namespace Yesod
{
public class Program
{
//
//
//
public struct Particle
{
public byte type;
}
//
//
//
public class Entity<T>
{
public Entity<Entity<T>> Parent
{ get; private set; }
//
//
//
public Entity(Entity<Entity<T>> parent)
{
this.Parent = parent;
}
}
//
//
//
public sealed class Atom : Entity<Particle>
{
public Atom(Entity<Atom> parent)
: base(parent) // Compile Error.
{ }
}
//
//
//
public sealed class Molecule : Entity<Atom>
{
public Molecule()
: base(null)
{ }
}
static void Main(string[] args)
{
}
}
}
How would I solve the following compile error that the above produces?
Argument 1: cannot convert from 'Yesod.Program.Entity<Yesod.Program.Atom>' to 'Yesod.Program.Entity<Yesod.Program.Entity<Yesod.Program.Particle>>'
Comment Reply #1:
Specifically, the code is trying to assign an object of type
Entity<Atom>
to an object of type
Entity<Entity<Particle>>
as Atom is implemented as
public sealed class Atom : Entity<Particle>
whereby
Entity<Atom>
is expected to breakdown into
Entity<Entity<Particle>>
Although the potential solution posted by Daniel Martin would never work (as admittedly warned), the explanation on why my code would too never work is 100% accurate, and it has led me to discover that C# 4.0 solves this otherwise expected functionality using its new generic covariance & contra-variance language features.
Below is the solution, for review:
Thanks Daniel Martin. I could not 1-up you due to my current rep. score. To those wondering, the above is a silly mock up aimed to highlight obvious parent-child relationships to help those understand the question. The real-world intended use will be an advanced version that will be employed in the field of computer graphics to solve the Coherent Space Partitioning problem in a well-defined and recursive manner.