locked
Specified cast is not valid error RRS feed

  • Question

  • User244646 posted

    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?

    Friday, March 31, 2017 4:59 PM

All replies

  • User291989 posted

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

    Friday, March 31, 2017 7:23 PM
  • User244646 posted

    @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);

    Friday, March 31, 2017 7:45 PM
  • User244646 posted

    @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?

    Friday, March 31, 2017 9:17 PM
  • User291989 posted

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

    Saturday, April 1, 2017 6:50 PM