2

so far my code does the following.

  1. Ask user for a numeric amount for 'players'
  2. Then asks for names for each of the players which is added to a list and class

I'd like to call those names from the list or class (not really sure how class works) and assign it to a new string. Here's what I got so far:

public class NameVariable
{
    public int ID { get; set; }
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        bool IsUserWrong = false;

        Console.WriteLine("Write amount of players");

        while (!IsUserWrong)
        {
            int TotalPlayers;
            while (!Int32.TryParse(Console.ReadLine(), out TotalPlayers))
            {
                Console.WriteLine("Value must be numeric.");
            }

            if (TotalPlayers >= 12 && TotalPlayers <= 16)
            {
                List<NameVariable> PlayerList = new List<NameVariable>();

                for (int index = 0; index < TotalPlayers; index++)
                {
                    Console.WriteLine("Enter player {0}'s name:", index + 1);
                    PlayerList.Add(new NameVariable
                    {
                        Name = Console.ReadLine(),
                        ID = index
                    });
                }

                // string player1 = ???
                // string player2 = ???
                // and so on for 12-16 players
            } 
            else
            {
                Console.WriteLine("Please enter a value between 12 and 16.");
            }
        }
    }
}

I know that a foreach loop can be used to display all of the variables in the NameVariable class. Would just like to know how to assign each variable to a different string.

Before using the class I just used the list which worked by using

string player1 = PlayerList[0];
string player2 = PlayerList[1];
// and so on for the remaining players

Thanks in advance!

2
  • 1
    You don't need to. Just use the collection. Commented Sep 19, 2017 at 20:30
  • Collections are supposed to replace numbered variables like that; no need for them now. Commented Sep 19, 2017 at 20:30

3 Answers 3

2

it's just

string player1 = PlayerList[0].Name;
string player2 = PlayerList[1].Name;
...

Essentially your list contains NameVariable objects. PlayerList[index] gives you the object, and .Name gives you the property value of the object.

If you want a specific player name by a specific ID number, you can use LINQ (just to give you a hint)

string player = PlayerList.Where(p => p.ID == WhateverIDNumber).First().Name;
Sign up to request clarification or add additional context in comments.

1 Comment

While this is all true, it should be pointed out that hardcoding it based on certain indexes defeats the purpose of using a collection in the first place.
1

While the answer to your immediate question, i.e., how to access properties of a class object, is as others have shown, I feel like this code has a bigger problem. That is you're trying to do too much in one function, namely, Main(). So I advice to in fact try and refactor your code so that one function does one thing. Something like:

public static int GetNumberOfPlayers()
{
    Console.Write("Enter number of players: ");
    int totalPlayers;
    while (!Int32.TryParse(Console.ReadLine(), out totalPlayers))
    {
        Console.WriteLine("Value must be numeric.");
    }
    return totalPlayers;
}

public static List<NameVariable> GetPlayerList(int num)
{
    var list = new List<NameVariable>();
    for (int i = 0; i < num; i++)
    {
        Console.WriteLine("Enter player {0}'s name:", i + 1);
        list.Add(new NameVariable
        {
            Name = Console.ReadLine(),
            ID = i
        });
    }
    return list;
}

public static void DisplayPlayers(List<NameVariable> list)
{
    foreach(var player in list)
    {
        Console.WriteLine("Player {0}, Name: {1}", player.ID, player.Name);
    }
}

public static void CantThinkOfAGoodName()
{
    while (true)
    {
        int totalPlayers = GetNumberOfPlayers();
        if (totalPlayers > 16 || totalPlayers < 12)
        {
            Console.WriteLine("Please enter a value between 12 and 16.");
        }
        else
        {
            var playerList = GetPlayerList(totalPlayers);
            DisplayPlayers(playerList);
            break;
        }
    }
}

public static void Main()
{
    CantThinkOfAGoodName();
    Console.ReadLine();
}

1 Comment

I've taken your advice and split up the sections in main to separate parts! Helps with using the same code over and over too.
0

Not sure if it helps but you can use an indexer to get players by name.

public NameVariable this[string name]

Let's say you create a class for the colection

public class NameColection : List<NameVariable>
{
    public NameVariable this[string name]
    {
        get
        {
            return this.FirstOrDefault(n => n.Name == name);
        }
    }
}

Then you access players by name

var players = new NameColection()
{
    new NameVariable() { ID = 1 , Name = "John" },
    new NameVariable() { ID = 2 , Name = "Paul" },
    new NameVariable() { ID = 3 , Name = "George" },
    new NameVariable() { ID = 4 , Name = "Ringo" }
};
var player1 = players["John"];

As NameColection inhertits from List, you will be able to add, remove or modify items the usual way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.