Learning About Methods

Welcome back! Now that you know how to define classes, attributes, and objects in C#, it's time to take the next step in our journey. In this lesson, we'll focus on methods, which are essential for adding behavior to your classes. Methods allow your objects to perform actions, making your programs dynamic and interactive.

What You'll Learn

In this lesson, we'll dive into methods: what they are, how to define them, and how to use them. A method in a class is a block of code that performs a specific task. In other words, it's an action that your objects can take. You'll learn how to add methods to your classes, and how to call these methods on objects.

Here's a quick example to get us started:

class Spaceship 
{
    // Public attribute
    public string? name;

    // Method to launch the spaceship
    public void Launch()
    {
        Console.WriteLine(name + " is launching into space!");
    }
}

class Program
{
    static void Main()
    {
        // Create an object of the Spaceship class
        Spaceship myShip = new Spaceship();

        // Set the name attribute
        myShip.name = "Voyager-1";

        // Call the Launch method
        myShip.Launch();
    }
}

In this example, the Launch method is defined in the Spaceship class. When you call myShip.Launch(), the program will print a message indicating that the spaceship is launching.

How to Define a Method in a Class

To define a method in a class, specify its access modifier, return type, name, and parameters (if any). Unlike normal functions, methods are defined within the scope of a class and can access the class's attributes and other methods. Methods often use the public keyword, making them accessible from outside the class.

Here's an extracted piece of code from the example:

C#
class Spaceship 
{
    // Public attribute
    public string? name;

    // Method to launch the spaceship
    public void Launch()
    {
        Console.WriteLine(name + " is launching into space!");
    }
}

In this example:

  • public is the access modifier, making the method accessible from outside the class.
  • void is the return type, indicating that the method does not return a value.
  • Launch is the method name.

Unlike normal functions, methods are tied to the object's state and can interact with the object's attributes. This encapsulates behavior within the class, making your code more organized and modular.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal