Object reference not set to an instance of an object when running xamarin.forms app


I was following the xamarin 101 series on youtube and got an error in episode 6 This is how my MainPageViewModel.cs is

    using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using Xamarin.Forms;

namespace App2.ViewModels
    class MainPageViewModel : INotifyPropertyChanged
        public MainPageViewModel()
            EraseCommand  new Command(() >
                TheNote  string.Empty;

            SaveCommand  new Command(() >
                TheNote  string.Empty;

        public ObservableCollection<string> AllNotes { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        string theNote;

        public string TheNote
            get > theNote;
                theNote  value;

                var args  new PropertyChangedEventArgs(nameof(TheNote));

                PropertyChanged?.Invoke(this, args);

        public Command SaveCommand { get; }
        public Command EraseCommand { get; }

and this is the MainPage.xaml file

<?xml version"1.0" encoding"utf-8" ?>
<ContentPage xmlns"http://xamarin.com/schemas/2014/forms"


            <RowDefinition Height"*"/>
            <RowDefinition Height"2*"/>
            <RowDefinition Height".5*"/>
            <RowDefinition Height"2*"/>
            <ColumnDefinition Width"*"/>
            <ColumnDefinition Width"*"/>

        <Image Source"vscode.png" BackgroundColor"PowderBlue" Grid.Column"0" Grid.Row"0" Grid.ColumnSpan"2"/>

        <Editor Grid.Column"0" Grid.ColumnSpan"2" Grid.Row"1" Placeholder"Enter note here" Text"{Binding TheNote}"/>

        <Button Grid.Row"2" Grid.Column"0" Text"Save" Command"{Binding SaveCommand}" BackgroundColor"Green"/>

        <Button Grid.Row"2" Grid.Column"1" Text"Delete" Command"{Binding EraseCommand}" BackgroundColor"Red"/>

        <CollectionView ItemsSource"{Binding AllNotes}" Grid.Row"3" Grid.ColumnSpan"2">
                            <Label Text"{Binding .}" FontSize"Title"/> 


The EraseCommand works fine but the SaveCommand throws an error System.NullReferenceException: 'Object reference not set to an instance of an object.' on line 21 of MainPageViewModel.cs

In the tutorial everything works fine but i get an error why is that? or how do i fix it?


AllNotes is null because you have never initialized it, so it throws a NullRef exception when you try to add an item to it


in your constructor add this line

AllNotes  new ObservableCollection<string>();

Answered By – Jason

Leave a Comment