Forum Xamarin.Android


The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

How to cast 'Java.Lang.Object' to specified class? Can't convert type 'Java.Lang.Object' to'MyClass'

SelvanSelvan USMember ✭✭
edited July 2015 in Xamarin.Android
namespace MyClass
    public class MenuItem
        public string Menu { get; set; }
        public int MenuImage { get; set; }

namespace MyClass
    [Activity (Label = "MainActivity", Icon = "@drawable/icon")]
    public class MainActivity : Activity 
        private ListView _listView;
        public static MenuItem[] menuItems = new MenuItem[0];
        public static int[] menu_images = { Resource.Drawable.Icon, Resource.Drawable.Icon2};
        public static string[] menu_value = { "Live Position", "Live Position2"};
        protected override void OnCreate(Bundle savedInstanceState)
            _listView = FindViewById<ListView>(Resource.Id.listview);
            menuItems = new MenuItem[menu_value.Length];
            for (int i = 0; i < menu_value.Length; i++) {
                menuItems [i] = new MenuItem ();
                menuItems [i].Menu = menu_value [i];
                menuItems [i].MenuImage = menu_images [i];
                _menuItemsList.Add (menuItems [i]);
            _listView.Adapter = new MyAdapter(this, _menuItemsList);
            _listView.ItemClick += (object sender, Android.Widget.AdapterView.ItemClickEventArgs e) => {
                Java.Lang.Object obj = e.Parent.GetItemAtPosition (e.Position);
                MenuItem mt = (MenuItem) obj; // I'm unable to cast in this line it show's error as Cannot convert type 'Java.Lang.Object' to 'MyClass.MenuItem' (CS0030) (MyClass)
                Console.WriteLine("Menu Clicked : " + mt.Menu);

I'm unable to cast in this line
"MenuItem mt = (MenuItem) obj;"
it show's error as Cannot convert type 'Java.Lang.Object' to 'MyClass.MenuItem' (CS0030) (MyClass)

Best Answers


  • ThamaraiThamarai Member ✭✭


    var propertyInfo = obj.GetType().GetProperty("Instance"); works fine.
    Thanks for all. It helped me a lot.

  • princepotemkinprincepotemkin Member ✭✭

    Eric ... you saved my sorry ass. Beers are on me, my friend ...

Sign In or Register to comment.