Forum Xamarin.iOS

Casting to Subclass

TapasBeheraTapasBehera USMember ✭✭
edited April 2017 in Xamarin.iOS

In my iOS native library, I have a class ClassA (has a property PropOne) which extends the super class ClassSuper.

In my Xamarin.IOS project I am trying to access the PropOne property from an object which is a member of class ClassA. But this object is returned as a ClassSuper.

public String example(ClassSuper object){  // object is a member of class ClassA
    ClassA obj = (ClassA) object;  // System.InvalidCastException has been thrown
    return obj.PropOne;
}

How to cast correctly?

Tagged:

Answers

  • TapasBeheraTapasBehera USMember ✭✭

    [BaseType(typeof(ClassSuper))]
    interface ClassA

  • TedRogersTedRogers USMember ✭✭✭✭

    I would do it like this:

    public String example(ClassSuper object){  // object is a member of class ClassA
        var obj = object as ClassA;
        if (obj != null) // if you know the class is the correct type, you could skip this check
            return obj.PropOne;
        else
            return ""; // or throw exception or return null
    }
    
  • TapasBeheraTapasBehera USMember ✭✭

    @TedRogers
    Thanks, Ted.The solution will work for C# classes.But this doesn't work when the classes are the native ios classes.I found a workaround so that I don't have to cast it.

Sign In or Register to comment.