Skip to main content

.NET Methods

Introduction

Methods are fundamental building blocks in .NET programming that allow you to organize code into reusable, logical units. A method is a block of code that performs a specific task and can be called from other parts of your program. Methods help in implementing the DRY (Don't Repeat Yourself) principle by encapsulating functionality that can be reused throughout your application.

In this tutorial, we'll explore how to create and use methods in C#, understand different types of parameters, return values, method overloading, and best practices for writing clean, effective methods.

Creating Your First Method

Let's start with a simple method that prints a greeting message:

csharp
using System;

class Program
{
static void Main(string[] args)
{
// Calling our method
DisplayGreeting();

Console.ReadKey();
}

// Method definition
static void DisplayGreeting()
{
Console.WriteLine("Hello! Welcome to .NET Methods tutorial.");
}
}

Output:

Hello! Welcome to .NET Methods tutorial.

Let's break down the components of a method:

  • static: This keyword indicates that the method belongs to the class itself, not to instances of the class.
  • void: This is the return type, indicating that this method doesn't return any value.
  • DisplayGreeting: This is the method name, following C# naming conventions (PascalCase).
  • (): These parentheses can contain parameters (in this case, none).
  • { }: The curly braces contain the method body—the code that executes when the method is called.

Methods with Parameters

Parameters allow you to pass data to a method. Let's enhance our greeting method to accept a name:

csharp
using System;

class Program
{
static void Main(string[] args)
{
// Calling method with a parameter
DisplayGreeting("Alice");
DisplayGreeting("Bob");

Console.ReadKey();
}

static void DisplayGreeting(string name)
{
Console.WriteLine($"Hello, {name}! Welcome to .NET Methods tutorial.");
}
}

Output:

Hello, Alice! Welcome to .NET Methods tutorial.
Hello, Bob! Welcome to .NET Methods tutorial.

Optional Parameters

C# allows you to define optional parameters with default values:

csharp
using System;

class Program
{
static void Main(string[] args)
{
// Using default value for the second parameter
DisplayGreeting("Alice");

// Providing both parameters
DisplayGreeting("Bob", "Advanced");

Console.ReadKey();
}

static void DisplayGreeting(string name, string level = "Beginner")
{
Console.WriteLine($"Hello, {name}! Welcome to the {level} .NET Methods tutorial.");
}
}

Output:

Hello, Alice! Welcome to the Beginner .NET Methods tutorial.
Hello, Bob! Welcome to the Advanced .NET Methods tutorial.

Named Arguments

Named arguments allow you to specify parameter values by name rather than position:

csharp
using System;

class Program
{
static void Main(string[] args)
{
// Using named arguments
DisplayInfo(name: "Charlie", age: 25);
DisplayInfo(age: 30, name: "Diana"); // Order doesn't matter with named arguments

Console.ReadKey();
}

static void DisplayInfo(string name, int age)
{
Console.WriteLine($"{name} is {age} years old.");
}
}

Output:

Charlie is 25 years old.
Diana is 30 years old.

Return Values

Methods can also return values using the return statement:

csharp
using System;

class Program
{
static void Main(string[] args)
{
int sum = AddNumbers(5, 7);
Console.WriteLine($"The sum is: {sum}");

// We can also use the return value directly
Console.WriteLine($"10 + 20 = {AddNumbers(10, 20)}");

Console.ReadKey();
}

static int AddNumbers(int a, int b)
{
return a + b;
}
}

Output:

The sum is: 12
10 + 20 = 30

In this example, AddNumbers has a return type of int instead of void, and it returns the sum of the two parameters.

Method Overloading

Method overloading allows you to define multiple methods with the same name but different parameter lists:

csharp
using System;

class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Sum of two numbers: {Add(5, 10)}");
Console.WriteLine($"Sum of three numbers: {Add(5, 10, 15)}");
Console.WriteLine($"Sum of decimals: {Add(3.5, 2.5)}");

Console.ReadKey();
}

// Method to add two integers
static int Add(int a, int b)
{
return a + b;
}

// Overloaded method to add three integers
static int Add(int a, int b, int c)
{
return a + b + c;
}

// Overloaded method to add two doubles
static double Add(double a, double b)
{
return a + b;
}
}

Output:

Sum of two numbers: 15
Sum of three numbers: 30
Sum of decimals: 6

The compiler determines which method to call based on the number and types of the arguments provided.

Real-World Example: Calculator Class

Let's create a simple calculator class that demonstrates methods in a more practical context:

csharp
using System;

class Calculator
{
public int Add(int a, int b)
{
return a + b;
}

public int Subtract(int a, int b)
{
return a - b;
}

public int Multiply(int a, int b)
{
return a * b;
}

public double Divide(int a, int b)
{
// Check for division by zero
if (b == 0)
{
throw new DivideByZeroException("Cannot divide by zero");
}

return (double)a / b;
}
}

class Program
{
static void Main(string[] args)
{
Calculator calc = new Calculator();

// Using the calculator methods
Console.WriteLine($"Addition: 15 + 7 = {calc.Add(15, 7)}");
Console.WriteLine($"Subtraction: 20 - 8 = {calc.Subtract(20, 8)}");
Console.WriteLine($"Multiplication: 6 × 4 = {calc.Multiply(6, 4)}");
Console.WriteLine($"Division: 25 ÷ 4 = {calc.Divide(25, 4)}");

try
{
Console.WriteLine($"Division by zero: {calc.Divide(10, 0)}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}

Console.ReadKey();
}
}

Output:

Addition: 15 + 7 = 22
Subtraction: 20 - 8 = 12
Multiplication: 6 × 4 = 24
Division: 25 ÷ 4 = 6.25
Error: Cannot divide by zero

This example shows how methods can be organized within a class to provide specific functionality. Notice that these methods aren't static because they are instance methods that belong to an object of the Calculator class.

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:

csharp
using System;

// Static class for extension methods
static class StringExtensions
{
// Extension method for string class
public static string Reverse(this string input)
{
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}

// Another extension method
public static bool IsPalindrome(this string input)
{
string reversed = input.Reverse();
return string.Equals(input, reversed, StringComparison.OrdinalIgnoreCase);
}
}

class Program
{
static void Main(string[] args)
{
string text = "Hello";

// Using the extension methods
Console.WriteLine($"Original: {text}");
Console.WriteLine($"Reversed: {text.Reverse()}");
Console.WriteLine($"Is '{text}' a palindrome? {text.IsPalindrome()}");

string palindrome = "radar";
Console.WriteLine($"Is '{palindrome}' a palindrome? {palindrome.IsPalindrome()}");

Console.ReadKey();
}
}

Output:

Original: Hello
Reversed: olleH
Is 'Hello' a palindrome? False
Is 'radar' a palindrome? True

The this keyword in the parameter list indicates that this is an extension method for the specified type.

Method Best Practices

Here are some best practices to follow when creating methods:

  1. Single Responsibility: Each method should perform one task and do it well.

  2. Descriptive Names: Use clear, descriptive method names that indicate what the method does.

  3. Parameter Management: Limit the number of parameters (generally to 7 or fewer).

  4. Method Length: Keep methods relatively short and focused.

  5. Error Handling: Validate inputs and handle potential exceptions gracefully.

  6. Documentation: Add comments to explain what the method does, its parameters, and return values.

Let's see an improved version of a method with these principles:

csharp
/// <summary>
/// Calculates the average of a list of grades and determines if the student passes.
/// </summary>
/// <param name="grades">List of grade values (0-100)</param>
/// <param name="passingGrade">Minimum average required to pass (default: 60)</param>
/// <returns>True if the student passes, false otherwise</returns>
/// <exception cref="ArgumentNullException">Thrown when grades is null</exception>
/// <exception cref="ArgumentException">Thrown when grades is empty or contains invalid values</exception>
public static bool DidStudentPass(List<int> grades, int passingGrade = 60)
{
// Validate input
if (grades == null)
{
throw new ArgumentNullException(nameof(grades), "Grades list cannot be null");
}

if (grades.Count == 0)
{
throw new ArgumentException("Grades list cannot be empty", nameof(grades));
}

// Check for invalid grades
if (grades.Any(g => g < 0 || g > 100))
{
throw new ArgumentException("All grades must be between 0 and 100", nameof(grades));
}

// Calculate average
double average = grades.Average();

// Compare with passing grade
return average >= passingGrade;
}

Notice how this method:

  • Has a clear name that explains what it does
  • Includes XML documentation
  • Validates inputs thoroughly
  • Has a specific, single responsibility
  • Uses descriptive variable names
  • Handles potential errors

Summary

Methods are essential building blocks in .NET programming that help you organize and reuse code. In this tutorial, we've learned:

  • How to define and call methods
  • Working with parameters and return values
  • Optional parameters and named arguments
  • Method overloading for flexibility
  • Extension methods to enhance existing types
  • Best practices for writing clean, effective methods

Methods are fundamental to object-oriented programming and are used extensively in .NET development. Mastering them is a crucial step in becoming a proficient C# developer.

Exercises

  1. Create a StringHelper class with methods to count vowels, consonants, and special characters in a string.

  2. Implement a MathUtils class with methods to calculate the factorial, check if a number is prime, and find the GCD of two numbers.

  3. Create a class for a bank account with methods for deposit, withdrawal, and checking balance. Include proper validation and error handling.

  4. Extend the int type with extension methods to check if a number is even, odd, prime, or a palindrome.

  5. Refactor the following code into multiple methods with clear responsibilities:

    csharp
    static void ProcessOrder(Order order)
    {
    // Validate order
    if (order == null) throw new ArgumentNullException(nameof(order));
    if (order.Items == null || order.Items.Count == 0)
    throw new ArgumentException("Order must contain items");

    // Calculate total
    decimal total = 0;
    foreach (var item in order.Items)
    {
    total += item.Price * item.Quantity;
    }

    // Apply discount
    if (total > 100)
    {
    total *= 0.9m; // 10% discount
    }

    // Calculate tax
    decimal tax = total * 0.07m;

    // Display summary
    Console.WriteLine($"Order Summary for {order.CustomerName}");
    Console.WriteLine($"Items: {order.Items.Count}");
    Console.WriteLine($"Subtotal: ${total:F2}");
    Console.WriteLine($"Tax: ${tax:F2}");
    Console.WriteLine($"Total: ${total + tax:F2}");
    }

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)