Creating and Calling Methods
In this chapter, we will delve into the creation and invocation of methods in C#. Methods are essential building blocks in programming, allowing us to encapsulate code for reuse and better organization. Let's explore the syntax and practical examples to understand how methods work.
Method Syntax
A basic method in C# can be defined using the following syntax:
csharp91234static returnDataType MethodName(parameters){// Code to be executed when the method is called}
static: Indicates that the method belongs to the class itself rather than an instance of the class;
returnDataType: Specifies the type of data the method will return. Use
void
if no data is returned;MethodName: The name of the method, which should be descriptive of its function;
parameters: Optional inputs to the method, enclosed in parentheses.
A Simple Method
Let's create a simple method called PrintHello
that prints a greeting message:
main.cs
1234static void PrintHello() { Console.WriteLine("Hello, World!"); }
To call this method, simply use:
main.cs
1PrintHello();
The result of execution such method is following:
main.cs
1234567891011121314151617using System; namespace ConsoleApp { class Program { static void PrintHello() { Console.WriteLine("Hello, World!"); } static void Main(string[] args) { PrintHello(); } } }
Method with a Loop
Consider a method CountToTen
that prints numbers from 1 to 10:
main.cs
1234567static void CountToTen() { for (int i = 1; i <= 10; i++) { Console.WriteLine(i); } }
Invoke this method using:
main.cs
1CountToTen();
Method in a Class
Methods are often part of a class. Here's how CountToTen
fits into a simple program:
main.cs
1234567891011121314151617181920using System; namespace ConsoleApp { class Program { static void CountToTen() { for (int i = 1; i <= 10; i++) { Console.WriteLine(i); } } static void Main(string[] args) { CountToTen(); } } }
In this example, CountToTen
is a static method within the Program
class. The Main
method is the entry point of the program, where CountToTen
is called.
Understanding methods is crucial for writing efficient and organized code. As you progress, you'll learn about methods with parameters and return types, enhancing your ability to create dynamic and reusable code blocks.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat