Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# class organization and lists

Tags:

c#

oop

list

I am working on a C# application which consists of objects Department, Course, and Section. Each Department has many Courses, and each Course has many Sections. Currently I have three classes: Department, Course, and Section. Department contains some properties and then a List Courses, which contains the courses the department offers. Course contains some properties and then a List Sections, which contains the sections of the course. Is this a good way to have the code structured or should I be doing it a different way?

Secondly, when I instantiate a department in my application, I set some properties and then would like to begin adding courses to the List Courses defined in the Department class. However, I seem to be unable to simply do Department.Courses.Add(Course) from the application. What must I do within the Department class so that I may add objects to that list without breaking the principle of encapsulation?

An example of what I have with the list right now is:

class Department
{

     // ......
     List<Course> Courses = new List<Course>;
}

however Department.Courses is not available in the program code after the class has been instantiated (all other properties of the class are available).

like image 634
Andrew Keller Avatar asked Apr 10 '26 14:04

Andrew Keller


1 Answers

Instantiate the internal Courses list inside the parameterless constructor of your class.

private List<Course> _coursesList;

public Department()
{
    _coursesList = new List<Course>();
}

Also, another way to ensure the encapsulation is to provide a method on your Department class to add the courses to it instead of directly exposing the courses list. Something like

public void AddCourse(Course c) { ... }

// or (adding the feature of doing the method calls in a composable way)
public Course AddCourse(Course c) { ... }

// or 
public void AddCource(String name, etc) { ... }

I think in your case it is not a good idea do directly exposes the List because the class List, may provide methods like, Add and Remove which could potentially creates an invalid state on your parent class. So if you choose to expose methods to manipulate the internal collections like I suggested, you could expose an array of Courses to your API clients (remember the arrays are read-only) so your API consumers won't be able to the create side effects on your department class.

public Course[] Courses {
    get { return _coursesList.ToArray(); }
}

In addition, you could also implement the IEnumerable interface on your Department class. It would enable you to take advantage of the all LINQ extension methods available in C# 3.0.

I hope it helps, Carlos.

like image 108
CARLOS LOTH Avatar answered Apr 12 '26 02:04

CARLOS LOTH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!