Specified cast is not valid error

philiphuynhphiliphuynh USMember ✭✭
edited March 2017 in Xamarin.Android

I have the following Java code I am trying to port over to C#:

private class SCRAHandlerCallback implements Handler.Callback {
        public boolean handleMessage(Message msg)
        {
            try
            {
                switch (msg.what)
                {
                    case MTSCRAEvent.OnDataReceived:
                        OnCardDataReceived((IMTCardData) msg.obj);
                        break;
            }
            catch (Exception ex)
            {

            }
            return true;
        }
    }

In C# I have the following code:

private class MyHandler : Java.Lang.Object, Handler.ICallback
        {
            public bool HandleMessage(Message msg)
            {
                switch (msg.What)
                {
                    case MTSCRAEvent.OnDataReceived:
                        OnCardDataReceived((IMTCardData)msg.Obj);
                        break;
                }
                return true;
            }

But an error appears at the following line "OnCardDataReceived((IMTCardData)msg.Obj);" stating
System.InvalidCastException: Specified cast is not valid.

What is the way to solve this issue?

Answers

  • WolfyeWolfye AUMember

    Not really an Android issue, but you could use the as operator to safely cast
    https://msdn.microsoft.com/en-us/library/cc488006.aspx

  • philiphuynhphiliphuynh USMember ✭✭
    edited March 2017

    @Wolfye said:
    Not really an Android issue, but you could use the as operator to safely cast
    https://msdn.microsoft.com/en-us/library/cc488006.aspx

    Thank you for your reply. I tried the "as" cast but when I tried to use the IMTCardData object inside the OnCardDataReceived it is actually null.

    OnCardDataReceived(msg.Obj as IMTCardData);

  • philiphuynhphiliphuynh USMember ✭✭
    edited March 2017

    @Wolfye said:
    Not really an Android issue, but you could use the as operator to safely cast
    https://msdn.microsoft.com/en-us/library/cc488006.aspx

    Thank you for your reply Wolfye. I have tried what you had suggested by doing
    OnCardDataReceived((IMTCardData)msg.Obj);

    But inside the OnCardDataReceived function it would throw an exception stating that the IMTCardData object passed in is NULL. I believe this is not the case because the msg.Obj does have value so maybe the casting is not correct.

    Is there any other way to solve this issue?

  • WolfyeWolfye AUMember

    Break on that line and evaluate the expression msg.Obj to see what it contains. I doubt it is an IMTCardData in that case.

Sign In or Register to comment.