Menu
Coddy logo textTech

Intro to Classes & Objects

Part of the Object Oriented Programming section of Coddy's C# journey — lesson 3 of 70.

A class is a blueprint for creating objects. An object is an instance of a class that contains data and behavior.

Define a simple class with properties

public class Dog
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Add a constructor to initialize the object

public class Dog
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public Dog(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

Add a method to define behavior

public class Dog
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public Dog(string name, int age)
    {
        Name = name;
        Age = age;
    }
    
    public string Bark()
    {
        return $"{Name} says Woof!";
    }
}

Create an object (instance) and use it

Dog myDog = new Dog("Buddy", 3);
Console.WriteLine(myDog.Bark());
Console.WriteLine($"Age: {myDog.Age}");

Output:

Buddy says Woof!
Age: 3

The new keyword creates an instance of the class, calling the constructor. You can create multiple objects from the same class, each with different data.

challenge icon

Challenge

Easy

Complete the Car class by adding a constructor and a Drive() method. Then create a Car object in Program.cs and use it.

The Drive() method should return: "The {Brand} is driving!"

Cheat sheet

A class is a blueprint for creating objects. An object is an instance of a class that contains data and behavior.

Define a class with properties:

public class Dog
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Add a constructor to initialize the object:

public class Dog
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public Dog(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

Add methods to define behavior:

public string Bark()
{
    return $"{Name} says Woof!";
}

Create an object using the new keyword:

Dog myDog = new Dog("Buddy", 3);
Console.WriteLine(myDog.Bark());
Console.WriteLine($"Age: {myDog.Age}");

Try it yourself

using System;

class Program
{
    static void Main()
    {
        string brand = Console.ReadLine();
        int year = int.Parse(Console.ReadLine());
        
        // TODO: Create a Car object with the input values
        
        // TODO: Print "Car: {brand} ({year})"
        
        // TODO: Call the Drive() method and print the result
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming