๐ŸŽ“ A1Learner
๐Ÿ”

C# Classes and Objects

A class is a blueprint that describes fields and methods for objects. An object is one item built from the class.

Build a Car object

The Car class has one public field named brand. Main builds a Car object and sets the field.

using System;

class Car
{
    public string brand;
}

class Program
{
    static void Main(string[] args)
    {
        Car car = new Car();
        car.brand = "Ford";
        Console.WriteLine(car.brand);
    }
}

Two objects, two brands

Main builds two Car objects. Each object gets its own brand value.

using System;

class Car
{
    public string brand;
}

class Program
{
    static void Main(string[] args)
    {
        Car first = new Car();
        first.brand = "Ford";
        Car second = new Car();
        second.brand = "Toyota";
        Console.WriteLine(first.brand);
        Console.WriteLine(second.brand);
    }
}

Change a field value

The brand field starts as Ford. A new value replaces it after the object is built.

using System;

class Car
{
    public string brand;
}

class Program
{
    static void Main(string[] args)
    {
        Car car = new Car();
        car.brand = "Ford";
        Console.WriteLine(car.brand);
        car.brand = "Honda";
        Console.WriteLine(car.brand);
    }
}

A method inside Car

ShowBrand is a method inside the Car class. The method prints the brand field of its own object.

using System;

class Car
{
    public string brand;

    public void ShowBrand()
    {
        Console.WriteLine(brand);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Car car = new Car();
        car.brand = "Ford";
        car.ShowBrand();
    }
}

Example

using System;

class Book
{
    public string title;
    public string author;

    public void Describe()
    {
        Console.WriteLine(title + " by " + author);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Book first = new Book();
        first.title = "Dune";
        first.author = "Frank Herbert";
        first.Describe();
        Book second = new Book();
        second.title = "Emma";
        second.author = "Jane Austen";
        second.Describe();
    }
}

Key points

  • A field is a variable declared inside a class.
  • Use new and the class name to build an object.
  • A dot joins an object name to a field or method.
  • Each object holds its own field values.
  • The public keyword lets code outside the class use a field or method.

In this example, the Book class holds a title field and an author field. Main builds the first book and sets its fields to Dune and Frank Herbert. Describe prints the first line with those values. Main then builds a second book for Emma by Jane Austen, and Describe prints the second line.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

What does new Car() do?