tags:

views:

165

answers:

4

Hi all,

First question here. I am trying to instantiate a generic class using the type of a field.

public class ValueRange<type1>
{
    type1 min;
    type1 max;
}

void foo()
{
    int k;
    ValueRange<k.GetType()> range;  
}

This doesn't work. Any suggestions?
Thanks in advance

+5  A: 

It takes a compile-time type, like so:

ValueRange<int> range;

It's also worth noting that you typically name your types "T"; it's just the generally-accepted standard (and hence nice to read).

Noon Silk
This actually doesn't answer the question. See Benjamins answer, that does.
James
James: Well, it's up to the OP to decide what answers the question :)
Noon Silk
"At runtime" was what gave it away for me - but I'm not yet sure if I parsed that correctly either :)
Benjamin Podszun
Benjamin: Yeah, but he seems to be a newbie, and it's a classic problem to make with generics, I think :) Nevertheless, let us see ... *places bets*
Noon Silk
+5  A: 

The sample is confusing. I suspect you want something like

Type genericType = typeof(ValueRange<>).MakeGenericType(k.GetType());
Activator.CreateInstance(genericType);
Benjamin Podszun
+1 although it would be `typeof(ValueRange<>)`.
Mark Seemann
Was about to post something similar!
James
@Mark: Fixed it, thanks for that.
Benjamin Podszun
A: 

You can instantiate the type at runtime, but you cannot declare the variable like you are doing.

Type genericType = typeof(ValueRange<>).MakeGenericType(k.GetType());
object instance = Activator.CreateInstance(genericType);

.NET 4.0 has new rules when it comes to covariance and contravariance of generic types. That should help in being able to more strongly type your variable.

Edit: changed example code to use helper variable genericType for readability.

Thorarin
A: 

To make it more clear. In the example above ValueRange is my class, not a c# one.

I wonder If there is any way to avoid declaring a type twice. int k; ValueType m;

In this declaration the type "int" is declared twice. But this seems to me to be redundant. If, for example, I want to change the type of k, I would have to change both declarations. I knew about "Activator.CreateInstance" but this doesn't look nice to me! Too complicated!! But if there is no better solution I'll stick to it

odysonline.gr