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.
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:
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.
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:
In this example:
publicis the access modifier, making the method accessible from outside the class.voidis the return type, indicating that the method does not return a value.Launchis 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.
