Kevin S. Miller
Kevin S. Miller

Reputation: 962

Extract type of object to use as generic <T>

I have a class VResult<T> that can be instantiated with

bool value = true;    
VResult<bool> vr =  new VResult<bool>(value);

If I don't know the type of value, I'd like to do something like

VResult<typeof value> = new VResult<typeof value>(value);

Is that possible?

The ultimate goal is to serialize/deserialize VResult<T>:

string json = JsonConvert.SerializeObject(new VResult<bool>(true));

where could be an object or basic datatype such as int or bool.

I'm using a data transfer object that adds

ValueTypeName = Value.GetType().Name;

and

ValueTypeNamespace = Value.GetType().Namespace;

properties so that on the receiving side I can use

JObject obj = JObject.Parse(json);
string vt = (string)obj["ValueTypeName"];
string vtn = (string)obj["ValueTypeNamespace"];
Type type = Type.GetType($"{vtn}.{vt}");
var value = Activator.CreateInstance(type);
value = obj["Value"];
VResult<typeof value> vr = new VResult<typeof value> (value); //not correct

to get all the Type information about value, but I just don't figure out how to get the generic <T> from value to pass it in the VResult<T> constructor;

Upvotes: 4

Views: 1441

Answers (1)

InBetween
InBetween

Reputation: 32780

You can create the generic instance like this:

object value = 1; //I don't know the runtime type of this
var genericType = typeof(VResult<>).MakeGenericType(value.GetType());
var genericInstance = Activator.CreateInstance(genericType, 
                                               new object[] { value });

And now you have a instance of VResult<int> with a value of 1. Is this what you were looking for?

Upvotes: 3

Related Questions