Utilizor
Contact Us

C# Classes/Objects

Detailed guide on creating classes and objects.

C# Classes and Objects

You learned from the previous chapter that C# is an object-oriented programming language.

Everything in C# is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

Multiple Classes

You can declare more than one class in the same file.

Examples

Two Classes

Using a class from Main.

using System;

class Car
{
  public string model = "Mustang";
}

class Program
{
  static void Main(string[] args)
  {
    Car myCar = new Car();
    Console.WriteLine(myCar.model);
  }
}

Object Fields

Objects contain their own data.

using System;

class Person
{
    public string name = "Unknown";
}

class Program
{
    static void Main()
    {
        Person p1 = new Person();
        p1.name = "Alice";
        Person p2 = new Person();
        // p2.name remains "Unknown"
        
        Console.WriteLine(p1.name);
        Console.WriteLine(p2.name);
    }
}