Notifications
Clear all
Topic starter 01/08/2025 11:50 pm
In C#, functions—officially called methods—are blocks of code you define once and can use repeatedly. They make your code organized, readable, and modular.
🏗️ Declaring a Function
public int Add(int a, int b)
{
return a + b;
}
public
: access modifier (others includeprivate
,protected
)int
: return typeAdd
: function name(int a, int b)
: parametersreturn
: sends a value back to the caller
Call it like this:
int result = Add(3, 4); // result is 7
🧭 Functions Without a Return (Void)
public void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
Here, void
means no value is returned.
🧩 Static vs. Instance Functions
- Static functions belong to the class itself:
public static void SayHi()
{
Console.WriteLine("Hi there!");
}
- Instance functions require an object to call them:
Dog myDog = new Dog("Fido", "Labrador");
myDog.Speak(); // Instance method
🧠 Optional & Named Parameters
public void SendEmail(string to, string subject = "Hello")
{
Console.WriteLine($"Email to {to} with subject '{subject}'");
}
SendEmail("user@example.com"); // Uses default subject
🌀 Overloaded Functions
You can define multiple versions with different parameters:
public void Print(string message) { Console.WriteLine(message); }
public void Print(int number) { Console.WriteLine(number); }
🌐 Async Functions (Advanced)
public async Task<string> FetchDataAsync()
{
await Task.Delay(1000); // Simulates a delay
return "Data loaded";
}