A function is a reusable block of code that performs a specific task. It helps divide a program into smaller parts, making it easier to read and maintain. It can take input (parameters), execute code, and optionally return a value.
- Promotes code reusability by avoiding repetition
- Improves readability and structure of the program
- Makes code easier to manage and maintain
using System;
class Program
{
// function definition
static int Square(int x)
{
return x * x;
}
static void Main()
{
// Calling the function
int result = Square(5);
Console.WriteLine("Square of 5 is: " + result);
}
}
Output
Square of 5 is: 25
Function Syntax in C#
A function in C# follows this general format:

Each part has a specific role:
- Return type: Specifies the type of value returned. Use
voidif no value is returned. - Function name: Name used to call the function.
- Parameter list: Inputs accepted by the function.
- Function body: Code executed when the function is called.
Function Declaration vs Definition
In C#, functions (methods) are usually declared and defined together inside a class.
static int Add(int a, int b)
{
return a + b;
}
Unlike C++, C# does not require separate declaration and definition in different files, methods are typically declared and defined together inside a class.
Calling a Function
A function is used by calling its name followed by parentheses, passing arguments if required.
using System;
class Program{
static void Greet() {
Console.WriteLine("Welcome to C# Programming!");
}
static int Multiply(int a, int b){
return a * b;
}
static void Main(){
Greet();
int result = Multiply(4, 5);
Console.WriteLine("Multiplication result: " + result);
}
}
Output
Welcome to C# Programming! Multiplication result: 20
Greet()is a parameterless method that prints a message.Multiply(int a, int b)takes two integers and returns their product.- Functions are called inside
Main()using their names.
Types of Functions in C#
Functions in C# can be categorized as:
1. Based on Origin
- Library Methods: Built-in methods provided by .NET, such as Console.WriteLine() and Math.Sqrt().
- User-Defined Functions: Functions created by the programmer.
2. Based on Input and Return Type
- No parameters, no return value
- Parameters, no return value
- No parameters, return value
- Parameters and return value
Note: Choosing the correct type of function improves code readability and flexibility. Functions help in reusing code and organizing large programs efficiently.