Exercise Solutions: Classes and ObjectsΒΆ

  1. Open up the file, Student.cs, and update the starter code to make use of auto-implemented properties.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
   public class Student
   {
      private static int nextStudentId = 1;
      public string Name { get; set; }
      public int StudentId { get; set; }
      public int NumberOfCredits { get; set; } = 0;
      public double Gpa { get; set; } = 0.0;

      public Student(string name, int studentId, int numberOfCredits, double gpa)
      {
         Name = name;
         StudentId = studentId;
         NumberOfCredits = numberOfCredits;
         Gpa = gpa;
      }

      public Student(string name, int studentId): this(name, studentId, 0, 0) { }

      public Student(string name): this(name, nextStudentId)
      {
         nextStudentId++;
      }
   }

Back to the exercises

  1. In Program.cs, instantiate the Student class using yourself as the student. For the NumberOfCredits give yourself 1 for this class and a GPA of 4.0 because you are a C# superstar!

1
2
3
4
5
6
   public static void Main(string[] args)
   {
   // TODO: Instantiate your objects and test your exercise solutions with print statements here.
   Student kimberly = new Student("Kimberly", 1, 1, 4.0);
   Console.WriteLine("The Student class works! " + kimberly.Name + " is a student!");
   }

Back to the exercises

  1. In the SchoolPractice project, create a class Course with at least three fields. Before diving into Visual Studio, try using pen and paper to work through what these might be. At least one of your fields should be a List or Dictionary, and you should use your Student class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
   // Create a new file Course.cs

   using System;
   using System.Collections.Generic;

   namespace SchoolPractice
   {
      public class Course
      {
         private string topic;
         private Teacher instructor;
         private List<Student> enrolledStudents;
      }
   }

Back to the exercises