2

I'm hoping that someone could explain how/why this does not work for determining a object's type dynamically then using the type in generics.

This will work because I'm specifying DateTime explicitly hardcoded as the type:

string serializedObject = JsonConvert.SerializeObject(exampleObject);
Type dataType = exampleObject.GetType();
JObject jObject = JObject.Parse(serializedObject);
jObject.Value<DateTime>("propertyName");

However neither of these seem to work:

jObject.Value<typeof(dateType)>("propertyName");
jObject.Value<dateType>("propertyName");

How can I specify the type of an property correctly here:

jObject.Value<{WHAT SHOULD I PUT HERE}>("propertyName");
dtb
  • 213,145
  • 36
  • 401
  • 431
jon333
  • 821
  • 2
  • 16
  • 28
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – nawfal Jan 17 '14 at 13:36

1 Answers1

0

It doesn't work because you are determining the dataType at runtime, however, Value<> needs to know the type at compile time. For one thing Value<T> might have constraints on what T must be, and it can't perform these checks at compile time on dataType if it doesn't know what dataType will be.

Here are some answers that address what you are trying to accomplish, although dealing with collections, applies to runtime determined generic parameters in general: Specifying generic collection type param at runtime

Note that your "{WHAT SHOULD I PUT HERE}" is what they are calling the generic parameter.

Community
  • 1
  • 1
AaronLS
  • 37,329
  • 20
  • 143
  • 202