C# Methods Basics
Introduction
Methods (also called functions in other programming languages) are one of the fundamental building blocks in C# programming. They allow you to organize your code into logical, reusable segments that perform specific tasks.
Think of methods as small machines that take some input, do some work, and potentially return a result. By using methods, you can:
- Avoid writing the same code multiple times (code reusability)
- Break down complex problems into smaller, manageable pieces
- Make your code more organized and readable
- Create modular components that can be tested independently
In this tutorial, we'll explore how to create and use methods in C#, starting with the very basics and building up to more practical examples.
Method Anatomy
Let's break down the structure of a C# method:
access_modifier return_type MethodName(parameter_list)
{
// Method body - code to be executed
return value; // Optional, required if return_type is not void
}
Let's understand each part:
- Access Modifier: Determines the visibility of the method (e.g.,
public
,private
,protected
) - Return Type: Specifies what type of data the method returns (e.g.,
int
,string
,bool
, orvoid
for no return value) - Method Name: The name you use to call the method (follows C# naming conventions, typically PascalCase)
- Parameter List: Input values the method needs to perform its task (can be empty)
- Method Body: The actual code that gets executed when the method is called
- Return Statement: Sends a value back to the code that called the method (required if return type is not
void
)
Your First Method
Let's start with a simple method that displays a greeting:
using System;
class Program
{
static void Main(string[] args)
{
// Calling the method
DisplayGreeting();
Console.ReadLine();
}
// Method definition
static void DisplayGreeting()
{
Console.WriteLine("Hello! Welcome to C# Methods.");
}
}
Output:
Hello! Welcome to C# Methods.
In this example:
DisplayGreeting
is the method namevoid
indicates the method doesn't return any valuestatic
means the method belongs to the class itself, not to instances of the class- The method has no parameters (empty parentheses)
Methods with Parameters
Parameters allow you to pass data to your methods. Let's create a method that greets a person by name:
using System;
class Program
{
static void Main(string[] args)
{
// Calling the method with different arguments
GreetPerson("Alice");
GreetPerson("Bob");
GreetPerson("Charlie");
Console.ReadLine();
}
static void GreetPerson(string name)
{
Console.WriteLine($"Hello, {name}! How are you today?");
}
}
Output:
Hello, Alice! How are you today?
Hello, Bob! How are you today?
Hello, Charlie! How are you today?
In this example:
name
is a parameter of typestring
- When we call the method, we provide an actual value ("Alice", "Bob", etc.) which is called an argument
- The method uses this value to create a personalized greeting
Methods with Return Values
A method can also return a value using the return
keyword. The return type in the method signature must match the type of value being returned:
using System;
class Program
{
static void Main(string[] args)
{
// Call the method and store the returned value
int sum = AddNumbers(5, 3);
Console.WriteLine($"The sum is: {sum}");
// Or use the returned value directly
Console.WriteLine($"10 + 20 = {AddNumbers(10, 20)}");
Console.ReadLine();
}
static int AddNumbers(int a, int b)
{
return a + b;
}
}
Output:
The sum is: 8
10 + 20 = 30
In this example:
AddNumbers
has a return type ofint
- It takes two integer parameters (
a
andb
) - It returns the sum of these parameters
- The calling code can use this returned value in various ways
Multiple Parameters
Methods can accept multiple parameters of different types:
using System;
class Program
{
static void Main(string[] args)
{
DescribeItem("Laptop", 999.99, true);
DescribeItem("Notebook", 4.99, false);
Console.ReadLine();
}
static void DescribeItem(string itemName, double price, bool isAvailable)
{
string availability = isAvailable ? "In stock" : "Out of stock";
Console.WriteLine($"{itemName} - ${price:F2} - {availability}");
}
}
Output:
Laptop - $999.99 - In stock
Notebook - $4.99 - Out of stock
Named Arguments
When calling methods with multiple parameters, you can use named arguments to make your code more readable:
using System;
class Program
{
static void Main(string[] args)
{
// Using positional arguments
DescribeItem("Smartphone", 699.99, true);
// Using named arguments (order doesn't matter)
DescribeItem(
isAvailable: false,
price: 1299.99,
itemName: "Gaming Console"
);
Console.ReadLine();
}
static void DescribeItem(string itemName, double price, bool isAvailable)
{
string availability = isAvailable ? "In stock" : "Out of stock";
Console.WriteLine($"{itemName} - ${price:F2} - {availability}");
}
}
Output:
Smartphone - $699.99 - In stock
Gaming Console - $1299.99 - Out of stock
Optional Parameters
You can make parameters optional by providing a default value:
using System;
class Program
{
static void Main(string[] args)
{
// Using all parameters
GreetUser("John", "Good morning");
// Using only the required parameter (name)
GreetUser("Sarah");
Console.ReadLine();
}
static void GreetUser(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}
}
Output:
Good morning, John!
Hello, Sarah!
Method Overloading
Method overloading allows you to define multiple methods with the same name but different parameter lists:
using System;
class Program
{
static void Main(string[] args)
{
// Different ways to call overloaded methods
PrintInfo("Alex");
PrintInfo("Alex", 28);
PrintInfo("Alex", "Developer");
Console.ReadLine();
}
// Method with one string parameter
static void PrintInfo(string name)
{
Console.WriteLine($"Name: {name}");
}
// Method with string and int parameters
static void PrintInfo(string name, int age)
{
Console.WriteLine($"Name: {name}, Age: {age}");
}
// Method with two string parameters
static void PrintInfo(string name, string occupation)
{
Console.WriteLine($"Name: {name}, Occupation: {occupation}");
}
}
Output:
Name: Alex
Name: Alex, Age: 28
Name: Alex, Occupation: Developer
The compiler determines which version of the method to call based on the argument types and count.
Real-World Example: Temperature Converter
Let's build a more practical example - a temperature converter that demonstrates several method concepts:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Temperature Converter");
Console.WriteLine("--------------------");
// Convert and display temperatures
double celsius = 25;
double fahrenheit = CelsiusToFahrenheit(celsius);
Console.WriteLine($"{celsius}°C = {fahrenheit}°F");
fahrenheit = 98.6;
celsius = FahrenheitToCelsius(fahrenheit);
Console.WriteLine($"{fahrenheit}°F = {celsius}°C");
// Display temperature description
DescribeTemperature(celsius, "C");
DescribeTemperature(fahrenheit, "F");
Console.ReadLine();
}
static double CelsiusToFahrenheit(double celsius)
{
return (celsius * 9 / 5) + 32;
}
static double FahrenheitToCelsius(double fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}
static void DescribeTemperature(double temperature, string scale)
{
string description;
// Normalize to Celsius for comparison if needed
double tempInCelsius = scale == "F"
? FahrenheitToCelsius(temperature)
: temperature;
if (tempInCelsius < 0)
description = "Freezing";
else if (tempInCelsius < 10)
description = "Very Cold";
else if (tempInCelsius < 20)
description = "Cool";
else if (tempInCelsius < 30)
description = "Warm";
else
description = "Hot";
Console.WriteLine($"{temperature}°{scale} is {description}");
}
}
Output:
Temperature Converter
--------------------
25°C = 77°F
98.6°F = 37°C
37°C is Hot
98.6°F is Hot
This example demonstrates:
- Methods with parameters and return values
- Method reusability (calling
FahrenheitToCelsius
from another method) - Using methods to organize code logically
Summary
In this tutorial, we've covered the basics of C# methods:
- Creating and calling methods
- Passing parameters to methods
- Returning values from methods
- Using named and optional parameters
- Method overloading
- Applying methods in a practical example
Methods are essential for organizing your code, making it more readable, reusable, and maintainable. As you advance in your C# journey, you'll discover more advanced method features like expression-bodied methods, method extensions, and async methods.
Exercises
To solidify your understanding of methods, try these exercises:
- Create a method that calculates and returns the area of a rectangle.
- Write a method that checks if a number is prime and returns a boolean.
- Create a set of overloaded methods for calculating different mathematical operations.
- Build a simple calculator application that uses methods for each operation.
- Create a method with optional parameters that formats a person's name in different ways.
Additional Resources
Now that you understand the basics of C# methods, you're ready to start organizing your code more effectively and building more complex applications!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)