I’m trying to get input from user using array of structs and then print it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CA4
{
class Program
{
static void Main(string[] args)
{
StudentDetails[,] student = new StudentDetails[5, 1];
Console.WriteLine("Please enter the unit code:");
student[0, 0].unitCode = Console.ReadLine();
Console.WriteLine("Please enter the unit number:");
student[1, 0].unitNumber = Console.ReadLine();
Console.WriteLine("Please enter first name:");
student[2, 0].firstName = Console.ReadLine();
Console.WriteLine("Please enter last name:");
student[3, 0].lastName = Console.ReadLine();
Console.WriteLine("Please enter student mark:");
student[4, 0].studentMark = int.Parse(Console.ReadLine());
for (int row = 0; row < 5; row++)
{
Console.WriteLine();
for (int column = 0; column < 1; column++)
Console.WriteLine("{0} ", student[row, column]);
}
Console.ReadLine();
}
public struct StudentDetails
{
public string unitCode; //eg CSC10208
public string unitNumber; //unique identifier
public string firstName; //first name
public string lastName;// last or family name
public int studentMark; //student mark
}
}
}
Unfortunately after entering all the data I get:
CA4.Program+StudentDetails
CA4.Program+StudentDetails
CA4.Program+StudentDetails
CA4.Program+StudentDetails
CA4.Program+StudentDetails
It doesn’t crash, just instead of the data that I entered get the above 5 lines.
I know that the reason why it doesn’t work is that I don’t use the structs correctly because without them there is no problem.
Can somebody please help me and tell me how to use structs propely in the example above. Thanks
Cheers,
n1te
Your call to
Console.WriteLine("{0} ", student[row, column]);is implicitly calling the ToString() method of the StudentDetails struct, which just writes out the name of the struct type by default. Override the ToString() method:However, the larger issue is that you are setting the properties of 5 different StudentDetails structs… by declaring an array
StudentDetails[,] student = new StudentDetails[5, 1];and asking the user to input details about the structs at different points in the array, i.e.student[0, 0]thenstudent[1,0], you aren’t making one StudentDetails object and setting properties on it, you created 5 different StudentDetails objects.Why are you using an array? If you want to the user to fill in a single StudentDetails object, just do
Then to write it out:
This will use the ToString() method you declared in your StudentDetails struct. (ToString() is called whenever an object needs to be converted to a string, you just don’t always have to write it)
Hope this helps.