1

I have a JSON deserializer (shown below) which works perfectly fine when I call it with a known type.

public static T Deserialize<T>(this object obj)
{
    var javaScriptSerializer = new JavaScriptSerializer();

    return (obj != null) ?
        javaScriptSerializer.Deserialize<T>(obj.ToString()) :
        default(T);
}

So this call will work:

var newExampleTypeX = exampleJsonString.Deserialize<ExampleTypeX>();

However, what I'm trying to do is pass in a type which is set at runtime and use it in place of the "ExampleTypeX". When I do I get the following compilation error:

Cannot resolve symbol 'someType'

So the declaration of someType looks like so (this is a simplified version):

var someType = typeof(ExampleTypeX);
var newExampleTypeX = message.Deserialize<someType>();

Should I be altering my Deserialize extension method somehow, or altering how I pass in the runtime type? If so then how do I achieve that.

Bern
  • 7,808
  • 5
  • 37
  • 47

1 Answers1

2

Type used with generics has to be know compile-time. That's why you can't do that:

var someType = typeof(ExampleTypeX);
var newExampleTypeX = message.Deserialize<someType>();

It's not connected with JavaScriptSerializer - that's how generics work.

If you really need to, you can use reflection to bypass that, but I don't think you should.

You can read more about using reflection with generic types and extension method in that two questions:

Generics in C#, using type of a variable as parameter

Reflection to Identify Extension Methods

Community
  • 1
  • 1
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • Thanks @MarcinJuraszek - if you have some code which illustrates how to achieve the above with reflection it would be greatly appreciated. – Bern Mar 08 '13 at 18:04
  • In the end I found the solution through the Json.NET framework. It provides a lot more functionality than the .NET JavaScriptSerializer. Instead of having my own extension method I simply used the JsonConvert.DeserializeObject(message, someType) – Bern Mar 15 '13 at 08:43