简体   繁体   中英

Null Reference Exception was unhandled C# console application

I know this is probably similar to some other posts, but I'm not quite sure what I'm doing wrong here. As an FYI, I'm new to programming and still trying to learn proper flow.

Here is the code, the exception occurs at "MyFriends[i].Name = friendName".

using System;
using System.Collections;

namespace FriendList
{
    class FriendList
    {
        static public Friend[] MyFriends = new Friend[2];
        public static void Main()
        {
            string friendName;
            string friendPhone, friendMonth, friendDay, friendYear;
            int intMonth, intDay, intYear;

            for (int i = 0; i < 2; ++i)
            {
                Console.Write("enter name");
                friendName = Console.ReadLine();
                MyFriends[i].Name = friendName;

                Console.Write("phone");
                friendPhone = Console.ReadLine();
                MyFriends[i].Phone = friendPhone;

                Console.WriteLine("Enter Month: ");
                friendMonth = Console.ReadLine();
                intMonth = Convert.ToInt32(friendMonth);
                MyFriends[i].Month = intMonth;

                Console.WriteLine("Enter Day: ");
                friendDay = Console.ReadLine();
                intDay = Convert.ToInt32(friendDay);
                MyFriends[i].Day = intDay;

                Console.WriteLine("Entery Year: ");
                friendYear = Console.ReadLine();
                intYear = Convert.ToInt32(friendYear);
                MyFriends[i].Year = intYear;
            }

            for (int i = 0; i < 2; ++i)
            {
                string information = string.Format("first name: {0}, phone {1}", MyFriends[i].Name, MyFriends[i].Phone);
                Console.WriteLine(information);
            }
            Console.Read(); 
        }
    }

    class Friend
    {
        string _Name = string.Empty, _Phone = string.Empty;
        int _Day = 0, _Month = 0, _Year = 0;

        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        public string Phone
        {
            get { return _Phone; }
            set { _Phone = value; }
        }

        public int Month
        {
            get { return _Month; }
            set { _Month = value; }
        }

        public int Day
        {
            get{ return _Day; }
            set{ _Day = value ; }
        }

        public int Year
        {
            get { return _Year;}
            set { _Year = value; }
        }

        public Friend()
        { }

    }
}

Thank you for your guidance!

Your friend array is initialized empty. So MyFriends[i] will hit a null reference, which is another way to say you are trying to access something that doesn't exist.

In other words, you have an Array with slots for two friends, but both slots are empty. You still need to have a friend in each slot before you can use their properties, such as Name , Phone etc.

Simply start the for loop like this:

for (int i = 0; i < 2; ++i)
{
    MyFriend[i] = new Friend(); //or pass parameters as required by the constructor
    // rest of your code goes here
}

And things will be fine. This way, you are adding a friend to the slot you will be using.

You've created an array with two elements, but you have set the elements to any value. They are both null :

static public Friend[] MyFriends = new Friend[2];

So, when you try to use MyFriends[i] from the array, you're actually getting null .

MyFriends[i].Name = friendName;

That where your NullReferenceException came from.


You'll have to initialize the members of the array. For example:

for (int i = 0; i < MyFriends.Length; i++)
{
    // Put a new Friend object in the array.
    MyFriends[i] = new Friend();

    // ...

When creating collections, they're populated with default values of the target type, and the default value for any reference type if null . So to solve your problem you'd have to initialize items in the array before accessing them:

....
for (int i = 0; i < 2; ++i)
{
    MyFriends[i] = new Friend();
    ...

MyFriends is an array of Friend class. each element in the array needs to be initialized with a friend constructor so it will be allocated with a memory.

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