Classes, Objects, and Methods

Building blocks of C# programs

Posted by Rodrigo Castro on November 10, 2024

Classes, objects, and methods are at the heart of C# programming.

🧱 Making a Class

A class is a template for creating objects.

1
2
3
4
5
6
7
8
class Animal
{
    public string Name;
    public void Speak()
    {
        Console.WriteLine($"{Name} makes a sound.");
    }
}

🐶 Creating an Object

An object is an instance of a class.

1
2
3
Animal dog = new Animal();
dog.Name = "Rex";
dog.Speak(); // Rex makes a sound.

🔧 Adding Methods

Methods are functions inside classes. They can use and modify the object’s data.

1
2
3
4
5
6
7
8
9
class MathHelper
{
    public int Square(int n)
    {
        return n * n;
    }
}
MathHelper helper = new MathHelper();
Console.WriteLine(helper.Square(4)); // 16

📝 Try It!

Write a class Book with a property Title and a method PrintTitle() that prints the title.

1
2
3
4
5
6
7
8
class Book
{
    public string Title;
    public void PrintTitle()
    {
        Console.WriteLine(Title);
    }
}

Next: Learn about encapsulation, inheritance, and polymorphism!