Type cast from Java.Lang.Object to native CLR type in MonoDroid

mironych picture mironych · Jul 6, 2011 · Viewed 12.4k times · Source

How to cast Java.Lang.Object to some native type?

Example:

ListView adapter contains instances of native type Message. When i am trying to get SelectedItem from ListView it returns instance of Message type casted to Java.Lang.Object, but I can't find solution to cast Java.Lang.Object back to Message.

var message = (Message)list.SelectedItem;
// throws  Error    5   Cannot convert type 'Java.Lang.Object' to 'Message'

Please Help.

Answer

mironych picture mironych · Jul 7, 2011

After long time debuging, have found the solution:

public static class ObjectTypeHelper
{
    public static T Cast<T>(this Java.Lang.Object obj) where T : class
    {
        var propertyInfo = obj.GetType().GetProperty("Instance");
        return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
    }
}

Usage example:

 var message = list.GetItemAtPosition(e.Position).Cast<Message>();
 bundle.PutInt("Message", message.ID);

After careful sdk study have found MonoDroid integrated extension for this purpose:

public static TResult JavaCast<TResult>(this Android.Runtime.IJavaObject instance)
where TResult : class, Android.Runtime.IJavaObject
Member of Android.Runtime.Extensions