Complete C# Tutorial

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 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 where T is a placeholder for any data type.
  • PrintValue<int>(100) โ†’ Calls the method with int.
  • PrintValue<string>("Hello") โ†’ Calls the method with string.
  • PrintValue<double>(99.99) โ†’ Calls the method with double.

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! ๐Ÿ˜ƒ

Leave a Comment

Share this Doc

Generic Methods in C#

Or copy link