Course Content
C# Basics
C# Basics
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:
- 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
static void PrintHello() { Console.WriteLine("Hello, World!"); }
To call this method, simply use:
main
PrintHello();
The result of execution such method is following:
main
using 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
static void CountToTen() { for (int i = 1; i <= 10; i++) { Console.WriteLine(i); } }
Invoke this method using:
main
CountToTen();
Method in a Class
Methods are often part of a class. Here's how CountToTen
fits into a simple program:
main
using 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.
Thanks for your feedback!