Classes and objects cheat sheet

Class vs object

Class is like a template. It has a description of everything, that belongs to the specific business concept it represents. For example:

class School
{
      private string _name { get; set; }
      private string _address { get; set; }
      private IList<StudyCourse> _studyCourses = new List<StudyCourse>();
}

Using this template in any other class, you could create an object (representation /implementation) of your class School:

var school = new School();
school.Name = "CodeEasy";
school.Address = "codeeasy.io"

When to use a constructor?

By default you always have an empty constructor. Like new School(). But in some cases you might want to create a custom one, so that it wouldn’t be possible to create a new object without some params. For example:

class School
{
     private string _name { get; set; }
     private string _address { get; set; }
     private IList<StudyCourse> _studyCourses = new List<StudyCourse>();

     public School(string name, string address) 
     {
            _name = name;
           _address = address;
     }
}

then you’ll use it as:

var school = new School("codeEasy", "codeeasy.io");

How to structure your code?

You usually create a structure, that represents “real life” as much as possible. If you create a school and admin departement of it, your classes should represent it in a way, that it’s easy to find and manage upgrades of your school.

Following this example: it’s most probable, that every StudyCourse of your school will look smth like:

class StudyCourse 
{
      private string _subject { get; set; }
      private Teacher teacher { get; set; }
      private IList<Student> students = new List<Student>();
}

So you’ll need to create as well such classes as Student, Teacher, etc.

Methods

It’s up to you to decide if a class should have any methods or not. Some will never have one and others will have dozens of different. When your structure your code, think about business logic.

For example methods assignNewStudent() or getTotalOfStudentsScoreA() should definitely belong to a StudyCourse, while getAvarageGrade() might belong to a Student if that’s we’re interested in.

Only one Main method

Remember however, that in the whole program the can be only one Main method! It contains everything you need to launch a program and initiates initial state, but should rather transfer as much of logic to other classes as possible.

1 Like