1 3_working_with_classes_and_objects
Jason Zhu edited this page 2021-02-23 13:57:37 +11:00

Module 3. Workinig with Classes and Objects

Creating a Class

In the simple Program.cs, there is already a class defined called Program, which contain a method Main

Task: encapsulate all grade calculation process in a class to simplify code

Note: Every class/method should be within a namespace. If not in a namespace, then the code fall into global namespace, which is dangerous.

Adding State

Creating a class definition is easy

namespace GradeBook
{
    class Program
    {
        static void Main(string[] args)
        {
            var book = new Book();

            //...
        }
    }

    class Book
    {
        
    }
}

A class has 2 types of members:

  1. State (data)
  2. Behavior (methods)

Defining a Method

        public void AddGrade(double grade)
        {
            
        }

Add Field Definition to class to contain state/data

List<double> grades;

The field definition has to be explicitly in type.

Adding a Constructor

All created class need a constructor, so objects can be initialized.

Separate a class to a separate .cs file, as long as files are within same namespace, no need to use sth like #include

Check C# Classes and structs -> Constructors

Requiring Constructor Parameters

  • Access Modifier
  • Args in constructor
  • keyword: this
    • It's an implicit variable that always available at all classes
    • It's optional if there is no conflict. But useful when need specify this object

W/o correct Access Modifier, other programs will mess up code usage.

Access Modifier provide encapsulation:

  • public
  • private
  • internal
  • internal

By assigning Access Modifier to class member, we can set visibility of these members

Working with Static Members

Static member of class vs. Instance member of class:

  • Static Modifier: Declare class member with static, makes it belong to class itself rather than objects.
  • Non-static members are "instance member"

Once a class method is static, then the data it use should also be static (not of instance)

Be careful of using static.

static member e.g. Console.WriteLine(), double.MinValue