Forum

Learn C# Functions
 
Notifications
Clear all

Learn C# Functions

1 Posts
1 Users
0 Reactions
11 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

 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 include private, protected)
  • int: return type
  • Add: function name
  • (int a, int b): parameters
  • return: 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";
}


   
Quote
Share: