Generics Methods in C# - Simple Guide with Examples
Introduction
Have you ever written a method that works for one data type but wished it could work for others too? Well, Generics Methods in C# let you do just that! They make your methods flexible, reusable, and type-safe.
Letโs explore what Generic Methods are, why they matter, and how to use them with simple examples.
๐ What You Are Going to Learn in This Lesson
โ๏ธ What are Generics Methods in C#?
โ๏ธ Why do we need Generic Methods?
โ๏ธ Syntax and explanation
โ๏ธ Simple examples with output
โ๏ธ A real-world use case
โ๏ธ A step-by-step explanation
๐ What are Generic Methods?
A Generic Method allows you to define a method with a placeholder for a data type. This means you donโt have to write separate methods for int, string, or doubleโone method works for all!
Example Problem:
Letโs say we want a method to print any type of value. Without Generics, we might do this:
void PrintInt(int value) { Console.WriteLine(value); }
void PrintString(string value) { Console.WriteLine(value); }
This works, but itโs not flexible. What if we need to print a double
or bool
? ๐ค
Thatโs where Generic Methods in C# come to the rescue! ๐
๐ Syntax of Generic Methods
Hereโs the basic syntax of a Generic Method:
public void MethodName<T>(T param) {
// Method body
}
โก๏ธ T
is a placeholder for a data type. When calling the method, T
is replaced with an actual type like int
, string
, or double
.
Now, letโs see this in action!
โจ Example 1: A Simple Generic Method
using System;
class Program {
// Generic Method
static void PrintValue<T>(T value) {
Console.WriteLine("Value: " + value);
}
static void Main() {
PrintValue<int>(100); // Works with int
PrintValue<string>("Hello"); // Works with string
PrintValue<double>(99.99); // Works with double
}
}
Output:
Value: 100
Value: Hello
Value: 99.99
๐ Explanation:
PrintValue<T>(T value)
โ A generic method whereT
is a placeholder for any data type.PrintValue<int>(100)
โ Calls the method withint
.PrintValue<string>("Hello")
โ Calls the method withstring
.PrintValue<double>(99.99)
โ Calls the method withdouble
.
Easy, right? ๐
๐ Example 2: Swapping Two Values Using Generics
using System;
class Program {
// Generic Swap Method
static void Swap<T>(ref T a, ref T b) {
T temp = a;
a = b;
b = temp;
}
static void Main() {
int x = 5, y = 10;
Swap(ref x, ref y);
Console.WriteLine($"Swapped values: x={x}, y={y}");
string first = "Hello", second = "World";
Swap(ref first, ref second);
Console.WriteLine($"Swapped values: first={first}, second={second}");
}
}
Output:
Swapped values: x=10, y=5
Swapped values: first=World, second=Hello
๐ Explanation:
- The
Swap<T>
method swaps two values without worrying about their data type! - Works for int, string, or any other type.
ref
is used to modify the original variables.
๐ Real-World Example: Logging System
Imagine we are building a logging system. We want to log messages, numbers, and even objects without writing multiple methods. Letโs use Generics Methods in C#!
using System;
class Logger {
// Generic Method for Logging
public void Log<T>(T message) {
Console.WriteLine($"[LOG]: {message}");
}
}
class Program {
static void Main() {
Logger logger = new Logger();
logger.Log("Application started"); // Logs a string
logger.Log(404); // Logs an integer
logger.Log(3.14); // Logs a double
}
}
Output:
[LOG]: Application started
[LOG]: 404
[LOG]: 3.14
๐ Why use Generics?
- One method handles multiple data types ๐
- No need to write separate logging methods
- Improves reusability and flexibility
โ Why Use Generic Methods?
โก๏ธ Code reusability โ Write once, use for all types!
โก๏ธ Type safety โ Prevents errors by ensuring data types match.
โก๏ธ Performance โ No need for boxing/unboxing (conversion between types).
ย
๐ Conclusion
We explored Generics Methods in C# and saw how they make code flexible and reusable. Whether printing values, swapping data, or logging messages, Generic Methods help us avoid repetitive code.
ย
๐ Next What?
In the next chapter, you will learn Generics Interfaces in C# and see how they work in real-world applications. Stay excited! ๐