Forum Xamarin.Android
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

How to prevent null pointer exceptions in C#

bunzunbunzun Member ✭✭


I come from Kotlin where code just works and where you generally don't have any NPE in running code. I am wondering if something similar exists in Xamarin.Android.

Take the onCreate function which takes a nullable Bundle. In C#, this variable isn't annotated as nullable. As such, you may receive a NPE in running code. The compiler doesn't warn you. As a developer, you just need to know that this variable may be null.

How can I force Visual Studio or the compiler to detect me misusing nullable variables to prevent runtime errors?


  • LandLuLandLu Member, Xamarin Team Xamurai

    We could add a ? to avoid the null exception like:

    var value = savedInstanceState?.GetBoolean("test");

    If you want to catch it, try:

        var value = savedInstanceState.GetBoolean("test");
    catch (Exception ex)
        Console.WriteLine("Variable is Null!");
  • bunzunbunzun Member ✭✭
    edited October 23
    This assumes you know that savedInstance is null. Visual Studio doesn’t mark the variable as nullable. In Kotlin/Android Studio, the bundle is already marked as nullable for you. Accessing the variable without null checking results in a compile time error?

    How long do you think C# will be as good as Kotlin?
  • LandLuLandLu Member, Xamarin Team Xamurai

    This appears to be a C# problem.
    We could still use a ? after the type to indicate this property is nullable:

  • bunzunbunzun Member ✭✭
    I know we can, but in my opinion we should not. It’s not up to developers to guess or figure out what platform code provides nullable variables. I’m going back to Kotlin cause I prefer writing apps that don’t crash
  • LandLuLandLu Member, Xamarin Team Xamurai

    Glad for sharing.

Sign In or Register to comment.