tuxmania tuxmania - 1 year ago 100
C# Question

Super type of generic object

i got a class like

class Btree<T> where T : IComparable { }

Now i want to write a controller that depending on the input creates an object.
But i don't want to rewrite the code for all possible types.
So i need something like:

Btree t = null;
if(input == "int")
t = new Btree<int>();
if(input == "string")
t = new Btree<string>();

After that i want to treat t no matter what type the btree actually is. Is this somehow possible?

Answer Source

To answer your question literally: Yes, you can do that using reflection. See the following question for details.

However, you shouldn't do that. Generics are a tool for compile-time type safety. If you don't need that (and from your example, it looks like you don't), simply using a Btree<IComparable> might be the most fitting solution for your problem:

var t = new Btree<IComparable>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download