Skip to content

Instantly share code, notes, and snippets.

@pedrolamas
Created September 12, 2014 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrolamas/fc47f1d0e32fc76a3986 to your computer and use it in GitHub Desktop.
Save pedrolamas/fc47f1d0e32fc76a3986 to your computer and use it in GitHub Desktop.
Xamarin UINavigationController.ViewDidLoad running before constructor
using System.Text;
using MonoTouch.UIKit;
namespace App2
{
public class CustomUiNavigationController : UINavigationController
{
private readonly StringBuilder _sb;
public CustomUiNavigationController(UIViewController uiViewController)
: base(uiViewController)
{
_sb = new StringBuilder();
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
_sb.Append("value"); //// null reference
}
}
}
@pedrolamas
Copy link
Author

I think I finally understand why I'm seeing this behavior: constructor is running first as one would expect, but the call to base constructor will cause ViewDidLoad to run before the full constructor ends (so in the example above, _sb hasn't been initialized yet!)

@pedrolamas
Copy link
Author

Confirmed by looking at call stack: the call order is base ctor -> ViewDidLoad -> local ctor.

I see that the expected .NET behavior for constructors is correct (sorry about that!), but in fairness doesn't make much sense to me to see the ViewDidLoad running from base ctor!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment