Methods
In C#, methods are blocks of code within a class
or struct
that perform specific tasks. They encapsulate functionality, promote code organization, and facilitate code reuse. Methods in C# have a signature that includes the method name, return type, and parameters (if any). Here's a basic overview of methods in C#:
Method Syntax
AccessModifier ReturnType MethodName(ParameterType1 parameter1, ParameterType2 parameter2, ...)
{
// Method body
// Perform actions
// Optionally return a value
}
- Access Modifier: Specifies the visibility of the method (e.g., public, private, internal).
- Return Type: Specifies the type of value the method returns (void if no return value).
- Method name: A unique identifier for the method within its class.
- Parameters: Input values passed to the method (optional).
- Method Body: The block of code executed when the method is called.
Program Methods
The Main
method serves as the entry point of a C# console application. It is the method that is automatically called when the program starts running. The Main
method has a specific signature and structure that is required by the C# language. Here is the standard structure of the Main method:
namespace ADEV.Module1.Methods
{
class Program
{
static void Main(string[] args)
{
// Code to be executed when the program starts
}
}
}
Organizing a program with methods is a fundamental practice in C# programming that promotes code modularity, readability, and maintainability. By breaking down a program into smaller, self-contained methods, you can encapsulate specific functionality, make the code more reusable, and improve overall structure.
namespace ADEV.Module1.Methods
{
internal class Program
{
static void Main(string[] args)
{
}
// Method to perform a specific task
static void MyMethod()
{
// Code for the task
}
// Method with parameters
static void AnotherMethod(int parameter1, string parameter2)
{
// Code that uses parameters
}
}
}
Warning
C# Console programs execute from a static
context. All methods within the Program
class must be declared using the static
access modifier.
Danger
It is common for C# beginners to declare and define methods outside of the class
block. If you are getting syntax errors declaring methods, double-check you've declared the method within the class block and not within the namespace or Main
method block.
Invoking Methods
Methods are invoked or called to execute their code. The process of invoking a method involves providing the necessary arguments (if any) and triggering the execution of the method's code.
static void Main(string[] args)
{
Console.WriteLine(Add(4, 5));
}
public static int Add(int a, int b)
{
return a + b;
}
Note
Because the Add()
method is within the same class, dot-notation is not required.
Methods For Objects
Check out the Classes section of these notes.