0

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?

tuxmania
  • 906
  • 2
  • 9
  • 28
  • Possible duplicate of [typeof: how to get type from string](http://stackoverflow.com/questions/15108786/typeof-how-to-get-type-from-string) – Silas Reinagel Aug 29 '16 at 20:05

2 Answers2

3

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>();
Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • object however does not implement IComparable and i need that since i have to compare on the key which is of type T – tuxmania Aug 29 '16 at 20:08
  • @tuxmania: Good point; use a `Btree` then. (I modified my answer.) – Heinzi Aug 29 '16 at 20:08
  • still Btree is not castable to Btree – tuxmania Aug 29 '16 at 20:10
  • @tuxmania: Correct. My point is that - from your example - it looks like you don't need a `Btree` *at all*. Instead of the example in your question, just use `Btree t = new Btree()`. – Heinzi Aug 29 '16 at 20:10
  • ok you are right but indeed i need it :) since i have to sort at some point the keys and it is different sorting 1 as int or as string. Btree t = new Btree() also does not work since Btree requires the generic parameter – tuxmania Aug 29 '16 at 20:11
  • @tuxmania: IComparable contains everything you need for sorting. Or do you need a custom sort order for strings? – Heinzi Aug 29 '16 at 20:13
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/122142/discussion-between-heinzi-and-tuxmania). – Heinzi Aug 29 '16 at 20:14
  • Solution indeed was to just use the super type as generic parameter that is IComparable in this scenario – tuxmania Aug 29 '16 at 20:24
0

Your "Btree t = null;" line is not valid to start if it is really a generic class.

BTree cannot be both generic and not generic at the same time. If it is a generic the type must be defined upon declaration of the variable "t".