C# Methods
Introduction
Methods are fundamental building blocks in C# programming. They are blocks of code designed to perform specific tasks and can be reused throughout your application. Methods help organize your code into manageable, logical segments that improve readability, maintainability, and encourage code reuse.
In C#, a method is a code block that contains a series of statements. When the method is called, these statements are executed. Methods can receive data as parameters, process it, and optionally return results.
Method Basics
Method Declaration Syntax
The basic syntax for declaring a method in C# is:
<access_modifier> <return_type> <method_name>(<parameters>)
{
// Method body
// Code statements
return <value>; // if return type is not void
}
Let's break down each component:
- Access modifier: Determines the visibility of the method (e.g.,
public
,private
,protected
) - Return type: Specifies the data type of the value the method returns (or
void
if it doesn't return a value) - Method name: A descriptive name following C# naming conventions (typically PascalCase)
- Parameters: Input values the method can work with (optional)
- Method body: The code that executes when the method is called
- Return statement: Returns a value to the caller (required if return type is not
void
)
Your First Method
Let's create a simple method that displays a greeting:
public void SayHello()
{
Console.WriteLine("Hello, World!");
}
To call this method:
SayHello(); // Output: Hello, World!
Parameters and Arguments
Methods can accept input data through parameters. When calling a method, you pass arguments to these parameters.
Basic Parameters
public void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
Calling this method:
Greet("Alice"); // Output: Hello, Alice!
Greet("Bob"); // Output: Hello, Bob!
Multiple Parameters
Methods can have multiple parameters of different data types:
public void DisplayPersonDetails(string name, int age, string occupation)
{
Console.WriteLine($"{name} is {age} years old and works as a {occupation}.");
}
Calling this method:
DisplayPersonDetails("John", 28, "Software Developer");
// Output: John is 28 years old and works as a Software Developer.
Optional Parameters
C# allows you to specify default values for parameters, making them optional:
public void ConfigureSettings(string username, bool enableNotifications = true, int maxItems = 10)
{
Console.WriteLine($"User: {username}");
Console.WriteLine($"Notifications: {enableNotifications}");
Console.WriteLine($"Max Items: {maxItems}");
}
You can call this method in multiple ways:
ConfigureSettings("user123");
// Output:
// User: user123
// Notifications: True
// Max Items: 10
ConfigureSettings("user456", false);
// Output:
// User: user456
// Notifications: False
// Max Items: 10
ConfigureSettings("user789", true, 20);
// Output:
// User: user789
// Notifications: True
// Max Items: 20
Named Arguments
Named arguments let you specify an argument by matching the parameter name:
ConfigureSettings(
username: "user101",
maxItems: 50,
enableNotifications: false
);
// Output:
// User: user101
// Notifications: False
// Max Items: 50
Note how we provided the arguments in a different order than the parameter declaration.
Return Values
Methods can return data back to the caller using a return statement.
Basic Return Value
public int Add(int a, int b)
{
return a + b;
}
Using this method:
int sum = Add(5, 3);
Console.WriteLine($"Sum: {sum}");
// Output: Sum: 8
// You can also use the return value directly
Console.WriteLine($"Result: {Add(10, 20)}");
// Output: Result: 30
Multiple Return Statements
A method can have multiple return statements, though only one will be executed:
public string GetGrade(int score)
{
if (score >= 90)
return "A";
else if (score >= 80)
return "B";
else if (score >= 70)
return "C";
else if (score >= 60)
return "D";
else
return "F";
}
Example usage:
Console.WriteLine($"Score 95: {GetGrade(95)}"); // Output: Score 95: A
Console.WriteLine($"Score 83: {GetGrade(83)}"); // Output: Score 83: B
Console.WriteLine($"Score 55: {GetGrade(55)}"); // Output: Score 55: F
Returning Multiple Values with Tuples
C# allows returning multiple values using tuples:
public (int Sum, int Product) CalculateSumAndProduct(int a, int b)
{
int sum = a + b;
int product = a * b;
return (Sum: sum, Product: product);
}
Using this method:
var result = CalculateSumAndProduct(5, 7);
Console.WriteLine($"Sum: {result.Sum}, Product: {result.Product}");
// Output: Sum: 12, Product: 35
// You can also deconstruct the tuple
var (sum, product) = CalculateSumAndProduct(3, 4);
Console.WriteLine($"Sum: {sum}, Product: {product}");
// Output: Sum: 7, Product: 12
Method Overloading
Method overloading allows you to define multiple methods with the same name but different parameter lists. The compiler determines which method to call based on the arguments provided.
// Method with two integer parameters
public int Add(int a, int b)
{
return a + b;
}
// Method with three integer parameters
public int Add(int a, int b, int c)
{
return a + b + c;
}
// Method with two double parameters
public double Add(double a, double b)
{
return a + b;
}
Example usage:
Console.WriteLine(Add(5, 10)); // Calls first method: Output: 15
Console.WriteLine(Add(5, 10, 15)); // Calls second method: Output: 30
Console.WriteLine(Add(5.5, 10.5)); // Calls third method: Output: 16.0
Expression-Bodied Methods
For simple methods, C# provides a more concise syntax using expression-bodied members:
// Traditional method
public int Multiply(int a, int b)
{
return a * b;
}
// Same method using expression body
public int Multiply(int a, int b) => a * b;
Both methods work identically:
Console.WriteLine(Multiply(6, 7)); // Output: 42
Practical Examples
Example 1: Temperature Converter
Let's create a utility class with methods to convert between temperature scales:
public class TemperatureConverter
{
public double CelsiusToFahrenheit(double celsius)
{
return (celsius * 9 / 5) + 32;
}
public double FahrenheitToCelsius(double fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}
public double CelsiusToKelvin(double celsius)
{
return celsius + 273.15;
}
public double KelvinToCelsius(double kelvin)
{
return kelvin - 273.15;
}
}
Usage:
TemperatureConverter converter = new TemperatureConverter();
// Convert 25°C to Fahrenheit
double tempInFahrenheit = converter.CelsiusToFahrenheit(25);
Console.WriteLine($"25°C is equal to {tempInFahrenheit:F1}°F");
// Output: 25°C is equal to 77.0°F
// Convert 98.6°F to Celsius
double tempInCelsius = converter.FahrenheitToCelsius(98.6);
Console.WriteLine($"98.6°F is equal to {tempInCelsius:F1}°C");
// Output: 98.6°F is equal to 37.0°C
// Convert 25°C to Kelvin
double tempInKelvin = converter.CelsiusToKelvin(25);
Console.WriteLine($"25°C is equal to {tempInKelvin:F2}K");
// Output: 25°C is equal to 298.15K
Example 2: String Manipulation Utility
Let's create a utility class with string manipulation methods:
public class StringUtility
{
public string Reverse(string input)
{
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public bool IsPalindrome(string input)
{
// Remove spaces and convert to lowercase
string processed = input.Replace(" ", "").ToLower();
return processed == Reverse(processed);
}
public int CountWords(string input)
{
if (string.IsNullOrWhiteSpace(input))
return 0;
// Split by spaces and count non-empty parts
return input.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
}
public string Capitalize(string input)
{
if (string.IsNullOrEmpty(input))
return input;
// Split into words, capitalize first letter of each word
string[] words = input.Split(' ');
for (int i = 0; i < words.Length; i++)
{
if (!string.IsNullOrEmpty(words[i]))
{
words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1).ToLower();
}
}
return string.Join(" ", words);
}
}
Usage:
StringUtility util = new StringUtility();
string sample = "Hello World";
Console.WriteLine($"Original: {sample}");
Console.WriteLine($"Reversed: {util.Reverse(sample)}");
Console.WriteLine($"Word Count: {util.CountWords(sample)}");
Console.WriteLine($"Capitalized: {util.Capitalize("hEllO woRLD")}");
Console.WriteLine($"Is 'radar' a palindrome? {util.IsPalindrome("radar")}");
Console.WriteLine($"Is 'hello' a palindrome? {util.IsPalindrome("hello")}");
// Output:
// Original: Hello World
// Reversed: dlroW olleH
// Word Count: 2
// Capitalized: Hello World
// Is 'radar' a palindrome? True
// Is 'hello' a palindrome? False
Ref and Out Parameters
C# provides two special parameter modifiers: ref
and out
.
Ref Parameters
The ref
keyword indicates that a parameter is passed by reference, allowing the method to modify the argument's value:
public void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
Usage:
int x = 10;
int y = 20;
Console.WriteLine($"Before swap: x = {x}, y = {y}");
Swap(ref x, ref y);
Console.WriteLine($"After swap: x = {x}, y = {y}");
// Output:
// Before swap: x = 10, y = 20
// After swap: x = 20, y = 10
Out Parameters
The out
keyword is similar to ref
but doesn't require the argument to be initialized before being passed to the method:
public bool TryParse(string input, out int result)
{
result = 0; // Must initialize out parameters
if (int.TryParse(input, out int parsed))
{
result = parsed;
return true;
}
return false;
}
Usage:
if (TryParse("123", out int number))
{
Console.WriteLine($"Successfully parsed: {number}");
}
else
{
Console.WriteLine("Failed to parse");
}
// Output: Successfully parsed: 123
if (TryParse("abc", out int invalidNumber))
{
Console.WriteLine($"Successfully parsed: {invalidNumber}");
}
else
{
Console.WriteLine("Failed to parse");
}
// Output: Failed to parse
Extension Methods
Extension methods allow you to "add" methods to existing types without modifying the original type. They are defined as static methods in static classes.
public static class StringExtensions
{
public static bool IsValidEmail(this string input)
{
// Simple email validation
if (string.IsNullOrEmpty(input))
return false;
return input.Contains("@") && input.Contains(".");
}
public static string Truncate(this string input, int maxLength)
{
if (string.IsNullOrEmpty(input) || input.Length <= maxLength)
return input;
return input.Substring(0, maxLength) + "...";
}
}
Usage:
// Need to include the namespace where extensions are defined
string email = "[email protected]";
Console.WriteLine($"Is valid email: {email.IsValidEmail()}");
// Output: Is valid email: True
string longText = "This is a very long text that needs to be truncated for display purposes.";
Console.WriteLine(longText.Truncate(20));
// Output: This is a very long...
Summary
In this comprehensive guide to C# methods, we've covered:
- Basic method declaration and invocation
- Parameters and arguments, including optional and named parameters
- Return values and how to return multiple values using tuples
- Method overloading for creating multiple methods with the same name
- Expression-bodied methods for concise syntax
- Practical examples showing real-world applications
- Ref and out parameters for passing arguments by reference
- Extension methods to add functionality to existing types
Methods are a fundamental concept in C# programming that help organize code, promote reusability, and create modular, maintainable applications. Mastering methods is essential for becoming proficient in C# development.
Additional Resources
Exercises
- Create a calculator class with methods for basic operations (addition, subtraction, multiplication, division).
- Write a method that checks if a number is prime.
- Create a method that converts a number to its word representation (e.g., 123 → "one hundred twenty-three").
- Implement a string extension method that counts the occurrences of a specific character.
- Create a method with optional parameters to format a person's name in different ways.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)