Dharun
Dharun

Reputation: 613

Reflection in Windows Phone

The following code fails when I invoke the method. No exceptions; everything just crashes. This code is in a Windows Phone 7 Portable Class Library, any idea what's going on?

public static object Deserialize(string input, Type type)
{
    var castMethod = typeof(ModelBase).GetMethod("Cast").MakeGenericMethod(type);
    object castedObject = castMethod.Invoke(null, new object[] { input });
    return castedObject;
}

public static T Cast<T>(string input)
{
    return JsonConvert.DeserializeObject<T>(input);
}

Upvotes: 0

Views: 1299

Answers (2)

Short answer:

You don't need reflection here at all. You can replace your Deserialize(string, Type) method (and get rid of Cast<T>) by simply calling JsonConvert.DeserializeObject(string, Type).

Longer answer:

Your Cast<T> method needlessly complicates things:

  • It has a type parameter T and returns a T object/value, but the calling method (Deserialize) doesn't care about this anyway; it returns an "untyped" object, so Cast could just as well return object too.

  • Having to transform a Type object into the corresponding type argument for T means that you need to do some type reflection. However, if Cast<T> were not generic — and as pointed out above, it doesn't have to be — you wouldn't need all that reflection.

  • As it turns out, Json.NET doesn't require a type parameter T, either. JsonConvert.DeserializeObject has a non-generic "overload" that accepts a Type object.

Therefore, get rid of your Cast<T> method and of your reflection detour and simply use the non-generic JsonConvert.DeserializeObject(string, Type) overload.

P.S.: Regarding your original question, according to the ECMA-335 standard, which describes the CLI (which is implemented by .NET, .NET Compact, Silverlight, and WP7), Reflection is not part of the Kernel library, but a separate but optional library. If it is absent on a particular platform (such as on WP7, AFAIK), Type objects are essentially to be treated as opaque objects from which you cannot derive other Type instances.

Upvotes: 1

trydis
trydis

Reputation: 3925

MakeGenericMethod is present but not supported in Silverlight for Windows Phone.

Check here under "platform notes": http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod(v=vs.95).aspx

Upvotes: 1

Related Questions