Class definition

Procedural Programming vs Object-Oriented Programming

Before the emergence of classes, languages such as C had no concept of classes. Programming languages without classes and objects like C are known as procedural programming.

Procedural Programming: A program is a sequence of instructions, with its core focus on optimising execution steps.

With classes available now, we can write object-oriented programming code.

Object-Oriented Programming: A program consists of a set of encapsulated classes. The core idea is to bundle data together with functions that operate on the data into logically related units, and these units are called classes.

Class Definition

A class is a data structure containing stored data and executable code. It holds two categories of members:

  1. Data Members: Store property data of objects, including Fields and Constants
  2. Function Members: Implement behavioural logic for objects, such as methods, properties, constructors, destructors, operators, indexers and events

A class is a collection encapsulating logically related data and functions, used to model things from the real world or abstract concepts.

In short, a class is a data structure made up of data and functions. You can create objects from a class. Data and members can be accessed via objects, and they can also be accessed from within the class itself.

Class Declaration

The class keyword only defines a class template and does not create object instances. A template contains three parts: class name, class members and class characteristics.

Syntax

class ClassName
{
    // Member declarations (fields, methods, etc., order is not mandatory)
}Code language: C# (cs)

Class declaration is often referred to as a class definition


class Program
{
    static void Main(string[] args)
    {
        AddCalculator addCalculator = new AddCalculator();
        SubCalculator subCalculator = new SubCalculator();
    }
}


class AddCalculator
{
    public int A { get; set; }
    public int B { get; set; }
    public int Add()
    {
        return A + B;
    }
}

class SubCalculator
{
    public int A { get; set; }
    public int B { get; set; }
    public int Subtract()
    {
        return A - B;
    }
}Code language: C# (cs)

In the sample code above, two classes are defined: one for addition calculations and another for subtraction. We instantiate both classes inside the Main function of the main program.

Content sourced from foxdevelop.com

Class declarations do not have to appear top-down. You may define classes later in your source file and call them inside preceding Main functions. A class works merely as a blueprint. Code execution does not flow strictly top-down; it starts from the Main function and loads the corresponding class blueprint whenever needed.

Class Members

Fields

Fields are variables belonging to a class. They can be built-in types or custom types and support read and write operations.

Type FieldName;
class MyClass
{
    int MyField; // Field MyField of type int
}Code language: C# (cs)

A key difference from C/C++: C# has no global variables. All fields must be declared inside a type (class or struct).

Field Initialisation Rules

(1) Implicit Initialisation (no assigned value)

The compiler automatically assigns a default value matching the data type; default values differ across types.

int F1;    // Default value 0
string F2; // Default value nullCode language: JavaScript (javascript)

The table below lists C# data types and their corresponding default values for fields. Local variables must be explicitly initialised by developers.

Basic Value Types

Data TypeDefault ValueDescription
sbyte0Signed 8-bit integer
byte0Unsigned 8-bit integer
short0Signed 16-bit integer
ushort0Unsigned 16-bit integer
int0Signed 32-bit integer
uint0Unsigned 32-bit integer
long0LSigned 64-bit integer
ulong0ULUnsigned 64-bit integer
float0.0fSingle-precision floating point
double0.0dDouble-precision floating point
decimal0.0mHigh-precision decimal
char'\0' (null character, ASCII 0)Single character
boolfalseBoolean
Enum EnumThe enumeration member corresponding to underlying integer 0Enums are backed by integers and default to zero
Struct structAll fields assigned their respective default valuesCustom value type; all members zero-initialised

Reference Types

All reference types default to null, meaning they do not point to any object allocated on the heap.

In other words, no memory address is stored. Recall the memory diagram covered earlier: reference variables hold addresses such as 000001 01010 pointing to heap memory. When set to null, no valid address is stored.

Type CategoryExample TypesDefault Value
Built-in reference typesstring, objectnull
Custom class classPerson Student null
Arrays (any dimension)int[], string[,]null
Delegates / EventsAction, Func, custom delegatenull
Interface interfaceAny interface variablenull

Examples

string str;        // Default null
Student jason;     // Custom class, default null
int[] arr;         // Array, default null
Action callback;   // Delegate, default nullCode language: JavaScript (javascript)

Nullable Types (Nullable / T?)

Appending a question mark ? to primitive value types creates a nullable variant that can hold no valid value. For instance, an int age; variable defaults to 0. If you want to represent an absence of value, declare it as int? age2;. This nullable integer accepts null assignments: int? age2 = null;

A nullable type is a wrapped ValueType with default value null, signifying “no valid value available”.

Declaration SyntaxDefault Value
int? numnull
bool? flagnull
decimal? pricenull
class Test
{
    int a;      // Automatically assigned 0
    string b;   // Automatically assigned null
    bool c;     // Automatically assigned false
}Code language: JavaScript (javascript)

(2) Explicit Initialisation

Assign values with = during declaration. The assigned value must be determinable at compile time; random runtime values or user input are not permitted here.

int days = 25;
string word = "foxdevelop";Code language: JavaScript (javascript)
(3) Shorthand for multiple fields of identical type

Multiple variables of the same type can be declared together separated by commas. Different types cannot be mixed within one declaration statement.

int player, blood = 25;
string title, subTitle = "hi welcome to foxdevelop.com";Code language: JavaScript (javascript)

Methods

Method Definition

A method is a named, reusable executable block of code, equivalent to member functions in C++. When invoked, it executes internal logic and returns control to the caller. Methods fall into two categories: those with return values and void methods without return values.

Four core components of a method

  1. Return type: Use void if no return value exists
  2. Method name
  3. Parameter list: Empty parentheses () required even with zero parameters
  4. Method body: Executable code enclosed inside {}

class Program
{
    static void Main(string[] args)
    {
        Robot robot = new Robot();
        robot.SayHello();
    }
}


class Robot
{
    public void SayHello()
    {
        Console.WriteLine("Hello everyone");
        Console.WriteLine("Welcome to visit foxdevelop.com");
    }
}Code language: C# (cs)

The public modifier before public void SayHello() allows this function to be accessed outside the class via objectName.MethodName(). Without the public modifier, access defaults to private. Private methods can only be called from within the class body; external code cannot invoke them even with an object instance such as robot.

Declaring Class Variables & Creating Instances

1. Core Characteristics of Reference Types

Classes belong to reference types. Data is stored across two memory regions:

  1. Stack: Holds reference variables (pointers to memory addresses)
  2. Heap: Stores the actual object data

2. Step-by-Step Object Instantiation

1 Only declare reference variable (stack memory allocated, no heap object)
Robot robot; 
// Only allocates space for reference on stack; value is undefined, no object exists on heap
Code language: JavaScript (javascript)
This line creates a stack variable intended to hold a reference (heap memory address) to a Robot instance, which is null and empty at this stage.

2 Allocate heap memory using the new operator

new TypeName();Code language: JavaScript (javascript)
  1. Allocates memory on the heap and automatically initialises all fields to default values
  2. Returns the reference address of the heap object and assigns it to the stack variable
robot = new Robot();
Code language: JavaScript (javascript)
class Program
{
    static void Main(string[] args)
    {
        Robot robot;
        robot = new Robot();
    }
}


class Robot
{
    void SayHello()
    {
        Console.WriteLine("Hello everyone");
        Console.WriteLine("Welcome to visit foxdevelop.com");
    }
}Code language: C# (cs)
3. Combine declaration and instantiation in one statement
Robot robot = new Robot();Code language: C# (cs)
class Program
{
    static void Main(string[] args)
    {
        Robot robot = new Robot();
    }
}Code language: C# (cs)

Class definition

Previous:

Leave a Reply

Your email address will not be published. Required fields are marked *