OSC#.007: C# Classes and Objects — Constructors, Properties and Encapsulation

A class definition branches into two independent object instances.

A C# class defines a reusable type that groups data and operations. An object is an instance of that type, with its own state. For infrastructure software, a class can represent a fictional ASIC inventory record without controlling real mining equipment. OSC#.007 extends OSC#.006: Methods and Parameters from reusable operations to reusable types.

Prerequisites and objectives

Install a supported .NET SDK in a local practice environment. Review OSC#.001: The .NET Toolchain and OSC#.002: Built-In Types.

  • Distinguish a class, object and reference variable.
  • Construct independent instances using a constructor and new.
  • Explain encapsulation through public getters, private setters and validation.
  • Predict how reference assignment affects shared object state.
  • Run a local console exercise and reason about invalid input.

Classes, objects and reference semantics

According to Microsoft Learn’s classes and objects tutorial, classes organize related data and behavior. A class declaration supplies the type definition; creating an instance with new invokes a constructor. Each instance normally maintains its own instance fields. A variable of a class type contains a reference rather than the object’s entire contents. Assigning one reference to another variable does not clone the object. Both references can designate the same instance.

The architecture of the exercise separates an application entry point from a model type. Program creates objects and requests operations. MinerRecord stores an identity and fictional wattage and checks permitted state changes. A static member belongs to the type rather than an individual instance; an instance method operates on the object used to invoke it.

Video: Microsoft Developer, C# Fundamentals for Beginners. The Understanding Classes segment begins at 4:04:51. Watch the classes segment. The source identity was checked; in-page playback has not been independently tested.

Constructors and encapsulation

A constructor has the class name and no return type. It initializes an instance and may reject invalid arguments before construction completes. An auto-implemented property supplies accessor syntax and compiler-generated backing storage. In the sample, Name has a public getter and is assigned inside the constructor. Watts exposes a public getter and a private setter. UpdateWatts rejects negative input before changing state. Encapsulation reduces accidental misuse; it is not authentication or an authorization boundary. A nonnegative teaching value alone cannot establish an acceptable electrical operating range.

Microsoft’s training on classes, properties and methods provides further accessor examples. For review of conditional validation, revisit OSC#.005: Conditions and Loops.

Local console lab

Create a fresh console project in a directory dedicated to practice. The following commands create and run local files only:

dotnet --version
dotnet new console -n MinerClassLab
cd MinerClassLab
# Replace Program.cs with the complete program below.
dotnet run

Replace Program.cs with the following complete program:

using System;

public sealed class MinerRecord
{
    public string Name { get; }
    public int Watts { get; private set; }

    public MinerRecord(string name, int watts)
    {
        if (string.IsNullOrWhiteSpace(name))
            throw new ArgumentException("Name required", nameof(name));

        Name = name;
        UpdateWatts(watts);
    }

    public void UpdateWatts(int watts)
    {
        if (watts < 0)
            throw new ArgumentOutOfRangeException(nameof(watts));

        Watts = watts;
    }
}

internal static class Program
{
    public static void Main()
    {
        var a = new MinerRecord("Lab-A", 3000);
        var b = new MinerRecord("Lab-B", 3200);
        MinerRecord alias = a;

        alias.UpdateWatts(2800);

        if (a.Watts != 2800 || b.Watts != 3200)
            throw new InvalidOperationException("State check failed");

        try
        {
            a.UpdateWatts(-1);
            throw new InvalidOperationException("Validation failed");
        }
        catch (ArgumentOutOfRangeException)
        {
            if (a.Watts != 2800)
                throw new InvalidOperationException("State changed");
        }

        Console.WriteLine($"{a.Name}: {a.Watts} W");
        Console.WriteLine($"{b.Name}: {b.Watts} W");
    }
}

The following output is expected if the SDK compiles the program and all checks succeed:

Lab-A: 2800 W
Lab-B: 3200 W

The assignment to alias does not create a second MinerRecord. Updating alias changes a, while b remains independent. A negative update raises an exception before the property changes. The sample has no network access, hardware interface or external package dependency. Compilation and execution were not independently performed in the publication preparation environment.

Additional instructional video

Video: .NET, C# for Beginners full course. Objects and classes chapter at 1:34:30. Source identity and chapter verified; in-page playback remains untested. A separate official instructional resource is Microsoft Learn: Understanding Classes.

Exercises and knowledge check

  • Create a third MinerRecord. Confirm that changing its Watts leaves a and b unchanged.
  • Predict the output if alias is reassigned to b before calling UpdateWatts(2800).
  • Attempt to assign a.Watts directly from Main. Explain the compiler rejection.
  • Construct an object with a blank name. Identify the expected exception and why it is useful.
  • Explain why negative-value rejection is insufficient for live ASIC power control.

Answer key

  • Each new instance has separate state; only the third record changes.
  • A remains 3000 W; B becomes 2800 W. The original assertion would fail.
  • The setter is private and inaccessible from Program.
  • ArgumentException; the constructor prevents a blank identifier.
  • Actual limits require manufacturer specifications, verified telemetry, authorization, and operational safeguards.

Conclusion

Classes allow software to represent related state and behavior through a defined contract. Constructors establish initial state, properties expose selected data, and methods enforce controlled changes. Reference identity explains why two variables may address the same object. These concepts prepare the learner for inheritance, interfaces and more complex infrastructure models.

References

Optional BitcoinVersus.Tech donation QR
Optional BitcoinVersus.Tech donation QR. Confirm recipient and amount before sending.

We volunteer daily to ensure the information on BitcoinVersus.Tech is Verifiably True. Educational examples do not replace certified controls or site safety procedures.

Leave a Reply