[Solved] Adding a Method


Sure, what you can do is create a method that takes in a list of students, gathers information about the new student from the user, and then adds a new student to the list. It would also need to ensure that if the list passed in was null, then it would initialize the list.

I’m guessing at what some of your student properties are. You can change them to match your Student class.

/// <summary>
/// Gets student information from the user and adds a new student to the list
/// </summary>
/// <param name="existingStudents">The list of students to add to</param>
private static void AddStudent(List<Student> existingStudents)
{
    // Initialize the list if it's null
    if (existingStudents == null) existingStudents = new List<Student>();

    int tempInt;

    // Get student information from the user
    Console.WriteLine("Enter new student information");

    do
    {
        Console.Write(" 1. Enter student Id: ");
    } while (!int.TryParse(Console.ReadLine(), out tempInt));
    var id = tempInt;

    Console.Write(" 2. Enter student Name: ");
    var name = Console.ReadLine();

    Console.Write(" 3. Enter student Job Title: ");
    var jobTitle = Console.ReadLine();

    do
    {
        Console.Write(" 4. Enter student years of service: ");
    } while (!int.TryParse(Console.ReadLine(), out tempInt));
    var yrsOfService = tempInt;

    // Add the new student to the list
    existingStudents.Add(new Student(id, name, jobTitle, yrsOfService));
}

Then you can just call this from your main method like:

case 3:
    AddStudent(st);
    break;

Note that in the beginning of your Main method, you never add the hard-coded students to your list. After you create your students, you may want to add something like:

st.Add(st1);
st.Add(st2);
st.Add(st3);

3

solved Adding a Method