Generics types and inheritance

            1. What are limitations of pure generic types?

            2. How we can manage with limitations of pure generic types?

When a generic type is already created we can’t work with another type, to avoid this we can create the base non-generic version of the type and cast to this base type  new created generic types.

 

Example:

    public class Node<T>

    {

        private Node<T> _nextNode;

        private T _data;

 

        public Node(T data, Node<T> nextNode)

        {

            _data = data;

            _nextNode = nextNode;

        }

 

        public Node(T data)

            : this(data, null) { }

 

        public override string ToString()

        {

            return _data.ToString();

        }

    }

 

    public class Node

    {

        protected Node _nextNode;

 

        private Node() { }

 

        protected Node(Node nextNode)

        {

            _nextNode = nextNode;

        }

    }

 

    public class TypedNode<T> : Node

    {

        private T _data;

 

        public TypedNode(T data, Node nextNode): base(nextNode)

        {

            _data = data;

        }

 

        public TypedNode(T data)

            : this(data, null) { }

 

        public override string ToString()

        {           

            return _data.ToString();

        }

    }

 

 

    class Program

    {

        static void Main(string[] args)

        {

            Node<string> head = new Node<string>("First");

            head = new Node<string>("Second", head);

            head = new Node<string>("Third", head);

 

 

            Node typedNodeHead = new TypedNode<string>("First");

            typedNodeHead = new TypedNode<Guid>(Guid.NewGuid(), typedNodeHead);

            typedNodeHead = new TypedNode<char>(‘A’, (Node)typedNodeHead);

        }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s