'Creating a Generice LinkNode Class in C#. If I pass "Int" as a Parameter to Typify <T> the Class. e.g public class ListNode<T> { }

public class ListNode<T>
{
    private ListNode<T> next;
    private T item;

    public ListNode<T> Next
    {
        get { return next; }
        set { next = value; }
    }

}

Will this be Reference type class or a Struct since Int is a struct. And the Field will it be a Reference or Value type. My confusion is Value type keeps their value however Reference Type point to heap memory where the actual value is stored. What will happen to ListNode class if I pass INT as a parameter.Will it be a value type or Reference, if value type then how the LinkNode Field will have the address of the next node.



Solution 1:[1]

class ListNode<T> is always a reference type - because you said 'class'. The fact that some fields might be value types (like if T is int) is not relevant.

Value types are stored 'inline' as opposed to being implemented as a pointer to the heap. So for ListNode<int> you will have

 next - pointer to heap allocated memory of next node
 item - the actual int

for ListNode<ClassObj>

 next - pointer to heap allocated memory of next node
 item - pointer to heap allocated memory of ClassObj item

When I say 'pointer' I do not necessarily mean a c style pointer that directly points to the heap memory location, but some implementation defined stucture that leads to the object

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1