Exercise Solutions: Classes and ObjectsΒΆ
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++;
}
}
|
In
Program.cs
, instantiate theStudent
class using yourself as the student. For theNumberOfCredits
give yourself1
for this class and a GPA of4.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!");
}
|
In the
SchoolPractice
project, create a classCourse
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 aList
orDictionary
, and you should use yourStudent
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;
}
}
|