Skip to content

C# Generic Class - change type parameter.

djmikeymike

Asked Mar 28, 2007, 7:02 PM EDT1 answer
Share
LinkedInX
Hi All,

I am on a learning curve from .net 1.1 to 2.0 and I am trying to get my head around generics.

As an excercise I am trying to create a linked list that can store data of multiple types.

As such I have created class Node<nodeDataType> and class MyLinkedList

I want to use the list class like this:

Code
MyLinkedList ll = new MyLinkedList();
ll.append<string>("foo");
ll.append<Exception>(new Exception());
ll.append<short>(-11);
My problem is this:

The MyLinkedList class needs to store a head node (private Node<???> _headNode;) which is null when created, and the type of object to be stored is not known until the first item is appended.

Is there a way of specifiying the type of a generic class at runtime or indeed changing the generic class type at runtime?

Cheers,

Mike.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Nope. Generics are designed to allow you to make re-usable type-safe code without relying on copy & paste for each specific type. For your example you want an instance to deal with multiple types, it's not what generics do. (Though you can use generics to apply to base classes or interfaces to allow them to work with any/all subclasses.)

    When looking at ways to apply generics it helps to think if there are relationships "of type" that can be applied. I.e. if you want a List "of type" MyClass, List<MyClass>, or a hash table "of type" MyClass with a key "of type" int (MyClass.MyID), Dictionary<int, MyClass>.

    You can apply generics for any number of scenarios from containers (See the Collections.Generic namespace since .Net 2.0 came with just about any you'll usually need.) to "utility" classes like those to help with keeping things uniform such as persistence, encryption, communication, etc.
    0