юрій бабій юрій бабій - 1 year ago 103
C# Question

Static constructor somehow blocks instance constructor

I have Xamarin.Forms app. Currently I am testing my app on Android and now I faced with issue that next view(page) is not showing. I started to debug it and where I stoped is when I am navigating to my page and then instance constructor is calling itself and in body of this constructor I have another initialization of another class that has static field and static methods. And when this static constructor is initializing my field then after this it is jumping over instance constructor and because of it I think it is not finishing to initialize all things but is actioning as done without actually navigation.
Here is it starts:

private void OnCreateNewUserButtonTapped()

then here:

public LoginingPageViewModel(INavigationService navigationService, IKeyboardHelper keyboardHelper, ISecuredDataProvider securedDataProvider)
_navigationService = navigationService;
_keyboardHelper = keyboardHelper;
_checkBox = new ShowPasswordCheckBoxModel();
_entries = new LogInPageEntriesModel();

_accountManager = new AccountManager(new ClientAuthorization(), securedDataProvider);

Func<bool> isLogInCommandEnable = () =>
StringService.CheckForNullOrEmpty(_entries.LoginText, _entries.PasswordText);

CheckedCommand = new DelegateCommand(OnCheckBoxTapped);
LogInCommand = new DelegateCommand(OnLogInTapped, isLogInCommandEnable);

And here is accountManager class where it is working not correct:

private readonly ClientAuthorization _clientAuthorization;
private readonly ISecuredDataProvider _securedDataProvider;
private static string _lastUser = GetLastUserFromStorage();
private readonly List<string> _users;

public AccountManager(ClientAuthorization clientAuthorization, ISecuredDataProvider securedDataProvider)
_clientAuthorization = clientAuthorization;
_securedDataProvider = securedDataProvider;
_users = _securedDataProvider.RetreiveAll(ConstantsService.ProviderName).Select(acc => acc.Username) as List<string>;
public static string GetLastUserFromStorage()

if ( Application.Current.Properties.ContainsKey("_lastUser") )
return Application.Current.Properties[_lastUser] as string;

return string.Empty;

If launch it without initialization "_lastUser" then it works perfect.

Answer Source

You want to put _lastUser in quotes when pulling the value out.


if ( Application.Current.Properties.ContainsKey("_lastUser") )
    return Application.Current.Properties["_lastUser"] as string;

Without that you'll be getting a stack overflow I'd say.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download