Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace AddtoUnknownListSize
- {
- /// <summary>
- /// A very basic class designed to take any string input for name and class.
- /// Using a declaration method we can set name and class as we create an object.
- /// </summary>
- class Program
- {
- class Player
- {
- public string playerName = "unknown";
- public string playerClass = "unknown";
- public Player(string pName, string pClass)
- {
- playerName = pName;
- playerClass = pClass;
- }
- }
- /// <summary>
- /// Since we dont always know how much data we want to keep an array may not always be
- /// the best solution. An array is great when we want to set how many objects we want but
- /// what if we didnt know if we wanted 1 players or 100 players? Well by using a list
- /// we can manipulate data in a similar way but not need to declare the ndex size as
- /// collections such as lists does that on the fly as we keep adding more objects.
- /// </summary>
- /// <param name="args"></param>
- static void Main(string[] args)
- {
- PrintWelcome();
- // Create a list collection. Very similar to how an array is created
- List<Player> gamePlayers = new List<Player>();// create list
- gamePlayers.Add(new Player("Player One", "Human"));// Set the first player in the list
- while (true)
- {
- foreach (var player in gamePlayers) // list how many players we currently have in the list
- {
- Console.ForegroundColor = ConsoleColor.Cyan;
- Console.WriteLine("Player Name: {0} \tPlayer Class: {1}", player.playerName, player.playerClass);
- Console.ResetColor();
- }
- Console.WriteLine();
- Console.Write("Do you want to create another player? (y) or (n):");
- string makeNewPlayer = Console.ReadLine();
- Console.WriteLine();
- if (makeNewPlayer == "y")
- {
- CreateAPlayer(gamePlayers); // Send our list called gamePlayers to the method below
- // to add more to the list.
- }
- else
- {
- Console.WriteLine("Thank you for looking at an example of collections"
- + "\nPress enter to end the program");
- Console.ReadLine();
- break;
- }
- }
- }
- //############ METHODS #################
- static void CreateAPlayer(List<Player> gamePlayers)
- {
- Console.WriteLine("Ok lets create a player!");
- Console.WriteLine();
- Console.Write("Choose your players name: ");
- string theName = Console.ReadLine();
- Console.Write("Choose your players class: ");
- string theClass = Console.ReadLine();
- gamePlayers.Add(new Player(theName, theClass)); // takes the name and class string and adds it to our list.
- Console.Clear();
- }
- static void PrintWelcome()
- {
- Console.WriteLine("AN EXAMPLE OF COLLECTIONS BY DEAN T (Twitter: @Dosk3n)"
- +"\nCODED FOR CODING 101 - WWW.TWIT.TV/CODE");
- Console.WriteLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement