Search code examples
c#xamarin.formsmvvmxamarin.android

Is there a way to check if a static object is null in C#?


I need to check if the endpoint value of my viewModel class is null, so I tried this:

   public static SettingsViewModel settingsViewModel { get; set; }

    public App()
    {
        InitializeComponent();

        if (UseMockDataStore)
            DependencyService.Register<MockDataStore>();
       
        MainPage = new AppShell();

        if(settingsViewModel.Endpoint==null)
        {
            Shell.Current.DisplayAlert("Endpoint Not Found", "There's no endpoint found in settings, please enter a valid endpoint", "OK");
        }
    }

But an exception of 'Object reference not set to an instance of an object', get thrown. Is there any other way to check if the endpoint value of my SettingsViewModel is null when the application starts? Appreciate the help!


Solution

  • if(settingsViewModel.Endpoint==null)
    

    This line only throws that exception, when settingsViewModel is null. Either this is a bug and you want to fix it, or if that is a real option at this point, you have to take it into account in your statement:

    if (settingsViewModel?.Endpoint == null)
    

    This will just check if there is a model and there is an endpoint. It does not care which one is null.