Home > Software engineering >  How can I set a string property from Console.ReadLine() inside a foreach loop?
How can I set a string property from Console.ReadLine() inside a foreach loop?

Time:05-01

I'm a newbie to programming and teaching myself. I am trying to wrap my head around simple multiplayer games using C#. I have a class Player with a single property of Name. I am trying to get the number of users from console input, create an array of the Player object of the size of that input, then for each object in the array ask the user to enter their name. When I try it, I get an object reference not set to an instance of an object error.

Here is my code:

using System;

namespace Multiplayer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("How many players?");
            int NumOfPlayers = int.Parse(Console.ReadLine());
            Player[] Players = new Player[NumOfPlayers];
            NameGetter(Players);     
            
        }
        static  void NameGetter(Player[] ListOfPlayers)
        {
            foreach(var player in ListOfPlayers)
            {
                Console.WriteLine("What is Your Name? ");
                player.Name = Console.ReadLine();
            }
        }
    }


}

I feel like I might be missing something fundament about OOP in my approach here.

Thanks very much in advance for any help I can get on this one!

CodePudding user response:

You've constructed an array of type Player, but you haven't constructed the Player objects eg: Players[0] = new Player(); will construct the first one, but you'll want to construct them in a loop.

CodePudding user response:

Just try to create your array with Enumerable.Range like this:

Player[] players = Enumerable.Range(0, NumOfPlayers).Select(x => new Player()).ToArray();

CodePudding user response:

if you see on the image, Know your array has 3 player types with the null value. so you must first create an object on here.

Your Code

**But **

You can't assign iteration variable

You can change Getter Method like

    static void NameGetter(Player[] ListOfPlayers)
    {
        for (int i = 0; i < ListOfPlayers.Length; i  )
        {
            Console.WriteLine("What is Your Name? ");
            ListOfPlayers[i] = new Player
            {
                Name = Console.ReadLine()
            };
        }
    }

Github Codes

  •  Tags:  
  • c#
  • Related