Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Inheritance c#

I have create a generic Node class which will be used to build a tree object. I want to inherit the attributes of this class in another. The job class represents a SQL job which is included in a chain (tree) of jobs. The following code is giving me an error and I am not sure why.

public class Node<T>
{
    public int id { get; set; }
    public Node<T> parent { get; set; }
    public List<Node<T>> Children = new List<Node<T>>();

    public bool isRoot
    {
        get { return parent == null; }
    }

    public static Node<T> createTree(List<Node<T>> nodes)
    {
        if (nodes.Count() == 0)
            return new Node<T>();
     //Build parent / Child relationships
    }
}

public class Job : Node<Job>
{
    public string name {get; set;}

    public Job(String name)
    {
        this.name = name;
    }
}


   List<Job> joblist = JobDict.Select(j => new Job(j.Key)).ToList();
   Node<Job>.createTree(joblist);

I am Unable to call createTree with the List of Jobs. I realize changing it from List < Job > to List < Node< Job > > works but why am I unable to do the former? I figured because I am inheriting the node class, a List of Jobs would in fact be equivalent to a List of Node. I am sorry if this is a very basic question but I just began with generics and inheritance and am having a hard time grasping it entirely.

like image 303
user1769667 Avatar asked Jun 13 '26 11:06

user1769667


2 Answers

The problem is that List<Node<Job>> and List<Job> are not co-variant.

If you're using .NET 4 you can do this.

Node<Job>.createTree((IEnumerable<Node<Job>>)joblist);

or, you can modify the creeatetree method definition as follows.

public static Node<T> createTree(IList  nodes)
{
    if (nodes.Count == 0)
    return new Node<T>();       

    //Build parent / Child relationships
} 
like image 97
Hari Prasad Avatar answered Jun 15 '26 01:06

Hari Prasad


I realize changing it from List<Job> to List<Node<Job>> works but why am I unable to do the former?

Because List<Job> does not inherit List<Node<Job>> even if Job inherits Node<Job>. In other words, A inherits B does not mean List<A> inherits List<B>.

You may need to cast each Job object to Node<Job> first:

var jobNodeList = joblist.Select(j => (Node<Job>)j).ToList();

Node<Job>.createTree(jobNodeList);
like image 27
Ian Herve Chu Te Avatar answered Jun 14 '26 23:06

Ian Herve Chu Te



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!