Sometimes you should create more than one constructor for a class. This is a useful practice, if you need to generate objects of the same type which need to be initiated with different fields. In the current example, we generate four objects – “Football Teams” and we define these football teams with a “Name”, “FamousPlayer”, “City” and “Country”. Furthermore, we develop a simple void method, which gives us information for those football teams.
The teams are put in an array and with a foreach loop the method given information is called. At the end of the program we have the following:
which is pretty much what we wanted to achieve.
One last interesting note – for the execution of the method the objects are put into an array. Then with the help of a foreach loop, the method is called for each one of them.
Here comes the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FootballNames { class ClubInfo { private string name; private string famousPlayer; private string city; private string country; public ClubInfo() { this.name = "Some name"; this.famousPlayer = "Some Player"; this.city = "some city"; this.country = "some country"; } public ClubInfo(string name, string famousPlayer, string city, string country) { this.name = name; this.famousPlayer = famousPlayer; this.city = city; this.country = country; } public void GiveInfo() { Console.WriteLine("{0} is from {1}, {2}. {3} plays there.",name,city, country,famousPlayer); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FootballNames { class Program { static void Main(string[] args) { ClubInfo FirstTeam = new ClubInfo(); ClubInfo SecondTeam = new ClubInfo("Manchester United", "Berbatov", "Manchester", "England"); ClubInfo ThirdTeam = new ClubInfo("Barca", "Messi", "Barcelona", "Spain"); ClubInfo ForthTeam = new ClubInfo("Real", "Ronaldo", "Madrid", "Spain"); ClubInfo[] myArray = new ClubInfo[] { FirstTeam, SecondTeam, ThirdTeam, ForthTeam }; foreach (ClubInfo myTeam in myArray) { myTeam.GiveInfo(); } } } } |