Casting return value of InstantiateViewController results in "cast is invalid" error or null

walkerj77walkerj77 Member ✭✭

I'm trying to instantiate a view controller from a storyboard bundled into my app.

In the storyboard, the view controller's Storyboard/Restoration ID and class are set up correctly. I'm able to instantiate the view controller, but as soon as I try to cast it, I run into issues.

var storyboard = UIStoryboard.FromName("MyStoryboard", NSBundle.MainBundle);
var viewController = storyboard.InstantiateViewController(nameof(MyViewController)); // This returns an object of type UIViewController
var castViewController = viewController as MyViewController; // castViewController gets set to null
castViewController.SomeCustomProperty = someValue; // This is why I need to cast viewController

If instead, I try var castViewController = (MyViewController)viewController; a "Specified cast is invalid" exception gets thrown.

As far as I can tell from documentation and examples online, the way I'm doing this should work. Is this a bug in Xamarin.iOS, or am I doing something wrong?

Sign In or Register to comment.