Generics Classes in C# Explained with Examples

So, you’re diving into C#, huh? Awesome! But sometimes, coding feels like juggling too many balls—especially when you’re stuck writing the same code over and over for different data types. Sound familiar? Don’t worry, buddy, that’s where Generics Classes in C# swoop in to save the day! Imagine writing one super-smart class that works with any data type—int, string, or even your own custom objects. Cool, right?

Let’s start with a quick example to get the vibe. Suppose you’re building a box to store stuff. Without generics, you’d need a separate box for apples, another for toys, and yet another for books. Exhausting! But with Generics Classes in C#, you create one magical box that can hold anything. Let’s break it down together!

Why Are Generics Classes in C# So Awesome?

First, let’s tackle the why. You’ve probably written code like this before: one method for int, another for string, and—ugh—so much repetition! It’s like doing the dishes twice. Generics Classes in C# fix that. They let you write flexible, reusable code that works with any type, safely. Plus, they catch errors at compile-time, not when your app crashes—huge win!

Think of generics as a Swiss Army knife. One tool, many uses. It’s important because it saves time, reduces bugs, and makes your code cleaner. Who doesn’t want that?

Syntax of Generics Classes in C# – Easy Peasy!

Here’s the basic blueprint for Generics Classes in C#:

				
					class MyGenericClass<T>
{
    public T MyValue;
}				
			
  • class MyGenericClass<T>: The <T> is the magic placeholder. It’s like saying, “Hey, I’ll figure out the type later!”
  • T: Stands for “Type.” You can name it anything—like TItem or TSuperCoolType—but T is the classic choice.
  • MyValue: A field of type T. It’ll hold whatever type you decide.

When you use it, you just tell it what T is:

				
					MyGenericClass<int> intBox = new MyGenericClass<int>();
intBox.MyValue = 42;				
			

See? Simple and sweet!

 

Example 1: A Simple Generics Class Program

Let’s whip up a quick Generics Classes in C# demo. Imagine a “Box” that can store anything:

				
					class Box<T>
{
    public T Item;

    public void AddItem(T item)
    {
        Item = item boda;
        Console.WriteLine($"Added: {Item}");
    }
}

class Program
{
    static void Main()
    {
        Box<int> numberBox = new Box<int>();
        numberBox.AddItem(123);

        Box<string> wordBox = new Box<string>();
        wordBox.AddItem("Hello, buddy!");
    }
}				
			

Output:

				
					Added: 123
Added: Hello, buddy!				
			

What’s Happening Here?

  • Box<T> is our generic class. It’s flexible like Play-Doh!
  • numberBox uses int, so T becomes int.
  • wordBox uses string, so T becomes string.
  • One class, two jobs. How cool is that?

Hey, how’s this making sense so far? Any struggles? Tell me—I’ve got your back!

Example 2: Swapping Values with Generics

Let’s have some fun! Ever tried swapping two values? Without Generics Classes in C#, you’d need separate methods for int, string, etc. Check this out:

				
					class Swapper<T>
{
    public void Swap(ref T a, ref T b)
    {
        T temp = a;
        a = b;
        b = temp;
    }
}

class Program
{
    static void Main()
    {
        Swapper<int> intSwapper = new Swapper<int>();
        int x = 5, y = 10;
        Console.WriteLine($"Before: x = {x}, y = {y}");
        intSwapper.Swap(ref x, ref y);
        Console.WriteLine($"After: x = {x}, y = {y}");
    }
}				
			

Output:

				
					Before: x = 5, y = 10
After: x = 10, y = 5				
			

Let’s Break It Down

  • Swapper<T> handles the swap logic.
  • ref T lets us change the original values.
  • Works with int here, but try it with string or double—it’s magic!

What do you think? Wanna try tweaking this code? Go for it!

 

Real-World Scenario: A Shopping Cart 🛒

Picture this: You’re coding an online store. You need a cart that holds books, gadgets, or clothes. Without generics, you’d make a BookCart, GadgetCart — ugh, too much work! With Generics Classes in C#, here’s a slick solution:

				
					class ShoppingCart<T>
{
    private List<T> items = new List<T>();

    public void AddToCart(T item)
    {
        items.Add(item);
        Console.WriteLine($"Added to cart: {item}");
    }

    public void ShowCart()
    {
        Console.WriteLine("Your cart:");
        foreach (T item in items)
        {
            Console.WriteLine(item);
        }
    }
}

class Program
{
    static void Main()
    {
        ShoppingCart<string> cart = new ShoppingCart<string>();
        cart.AddToCart("Cool T-Shirt");
        cart.AddToCart("Fancy Shoes");
        cart.ShowCart();
    }
}				
			

Output:

				
					Added to cart: Cool T-Shirt
Added to cart: Fancy Shoes
Your cart:
Cool T-Shirt
Fancy Shoes				
			

Why It Rocks

  • One ShoppingCart<T> works for any item type.
  • It’s reusable, clean, and oh-so-practical.
  • Imagine adding a Book class next—same cart, no sweat!

How’s this clicking for you? Feeling like a generics pro yet?

 

Example 3: Custom Objects with Generics

Let’s level up! Say you’ve got a Dog class:

				
					class Dog
{
    public string Name;
    public Dog(string name) { Name = name; }
    public override string ToString() { return Name; }
}

class Container<T>
{
    public T Content;
    public void Store(T content)
    {
        Content = content;
        Console.WriteLine($"Stored: {Content}");
    }
}

class Program
{
    static void Main()
    {
        Container<Dog> dogBox = new Container<Dog>();
        Dog myDog = new Dog("Buddy");
        dogBox.Store(myDog);
    }
}				
			

Output:

				
					Stored: Buddy				
			

What’s Cool Here?

  • Container<T> holds a Dog object like a champ.
  • T adapts to your custom type—no extra classes needed.
  • You’re in control, buddy!

Got any questions? How’s your coding journey going?

Conclusion

Wow, look at you go! We’ve explored Generics Classes in C# together, and now you’ve got the power to write flexible, reusable code. From simple boxes to shopping carts, you’ve seen how generics save time and headaches. Keep practicing—these skills will make you shine in any project. 

 

Next What? 🚪

Hey, guess what? In the next chapter, you’ll learn Generics Methods in C#! It’s like generics classes but with a twist—think of it as the sequel to this adventure. 

Leave a Comment

Share this Doc

Generic Classes in C#

Or copy link