简体   繁体   中英

Null reference c#

Im writing a code where you can search a name and the subjects teaches will pop-up etc..

however I'm not really sure why but i'm getting Object reference not set to an instance of an object error im missing something i know, can someone help me? i tried different methods didn't really work... heres my code:

public partial class MainWindow : Window
    {
        Course my = new Course();
        public class Course
        {

            public string[] Name { get; set; }
            public string[] Subject { get; set; }
            public string[] Hour { get; set; }

            public Course(string[] name, string[] subject, string[] hour)
            {
                this.Name = name;
                this.Subject = subject;
                this.Hour = hour;

            }
        }

        public MainWindow()
        {
            InitializeComponent();


            my.Name[0] = "Ali";
            my.Name[1] = "Sefer";

            my.Subject[0] = "INFORMATIKA";
            my.Subject[1] = "ENGLISH";

            my.Hour[0] = "12";
            my.Hour[1] = "22";

        }

        private void searchButton_Click(object sender, RoutedEventArgs e)
        {
            Find();
        }


        private void Find()
        {

            int index = 0;
            string wanted = wantedName.Text;

            while (my.Name[index] != wanted && (my.Name[index] != "END"))
            {
                index++;
            }
            if (my.Name[index] == wanted)
            {
                outputLabel.Content = " " + my.Name[index] + " "  + my.Subject[index];
            }
            else
            {
                outputLabel.Content = "Name not found";
            }
        }


    }
}

You are using arrays without initializing them. While you have defined a constructor for your Course class that takes values for the arrays, you are using the default constructor. Try calling your own constructor with arguments like

Course my = new Course(new string[2], new string[2], new string[2]);

Before you can assign a value to an element like my.Name[0] , you have to ensure that my.Name is referencing an allocated array, which means there is memory available for your elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM