LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
C# Programming

Generics in C# – Writing Reusable Code

Generics allow us to write reusable code that works with different data types. Instead of creating separate classes or methods for integers, strings and other types, we can use one generic implementation. Generics provide type safety, reduce duplicate code and avoid unnecessary type conversions. They are widely used in collections, repositories, APIs and enterprise applications.

1Writing Reusable Code with Generics

Hi friends, in this article we will learn generics in C#. Generics allow us to write reusable code that works with different data types. Instead of creating separate classes or methods for integers, strings and other types, we can use one generic implementation. Generics provide type safety, reduce duplicate code and avoid unnecessary type conversions. They are widely used in collections, repositories, APIs and enterprise applications.

2Think About a Reusable Storage Box

Imagine a storage box. Sometimes you store books, sometimes toys and sometimes documents. You need the same storage behaviour, but the stored item changes.

Generics work in a similar way. We create one generic class and decide its data type when creating an object. The same class can store an integer, string or another type safely.

Remember Generics allow one implementation to work with multiple data types while maintaining compile-time type safety.

3Understand Generic Types

Generic Class

A generic class uses a type parameter such as T. The actual type is supplied when creating an object.

Generic Method

A generic method defines its own type parameter. It can work with different types without rewriting the method.

Type Safety

The compiler checks the type during compilation. This helps prevent invalid assignments and reduces runtime casting errors.

Generic Constraints

Constraints restrict which types can be used. For example, where T : class requires a reference type.

Syntax Meaning
Box<T> Generic class
Method<T>() Generic method
where T : class Reference-type constraint
Pro Tip Use meaningful type parameters such as TKey and TValue when working with dictionaries.
Common Mistake Do not use object as a replacement for generics when you need compile-time type safety.

4Build Your First Generic Class

Let's create a reusable Box class. We will store an integer and a string using the same class. We will also create a generic method.

Program.csC#
using System;

class Box<T>
{
    public T Value { get; set; }
}

class Program
{
    static void PrintValue<T>(T value)
    {
        Console.WriteLine(value);
    }

    static void Main()
    {
        var numberBox = new Box<int>();
        numberBox.Value = 100;

        var textBox = new Box<string>();
        textBox.Value = "CSharp";

        PrintValue(numberBox.Value);
        PrintValue(textBox.Value);
    }
}

Here, T becomes int for numberBox and string for textBox. The compiler checks each assignment. PrintValue also detects the type from the supplied argument.

5Check the Program Result

Output
100
CSharp

The same Box class stores two different types. The generic method prints both values without requiring separate methods.

6Watch Generic Types in Action

Follow how the type parameter T becomes int and then string. Both objects use the same generic class.

Program.cs - Visual Studio Code
▤⌕⑂▦
● Program.cs
 
PROBLEMS  OUTPUT  DEBUG CONSOLE  TERMINAL
 
ReadyUTF-8  CRLF  C#

7Why Generics Matter

Generics help us write reusable and type-safe code. They reduce duplication and make applications easier to maintain. Collections such as List and Dictionary use generics internally.

  • Use T for reusable type parameters.
  • Use generic classes for reusable data structures.
  • Use generic methods for reusable operations.

8Questions Interviewers May Ask

Q1Easy

What are generics in C#?

Answer: Generics allow classes, methods and interfaces to work with different data types while maintaining compile-time type safety.

Q2Easy

What does T represent in generics?

Answer: T is a type parameter. The actual data type is supplied when using the generic class or method.

Q3Medium

What are generic constraints?

Answer: Constraints restrict the types allowed for a generic parameter. Examples include class, struct, new() and interface constraints.

Q4Medium

What is the difference between generics and object?

Answer: Generics provide compile-time type checking. Object can hold different types but may require casting and can introduce runtime errors.

Q5Hard

Why are generics useful for performance?

Answer: Generics can avoid boxing and unboxing for value types and reduce casting. This can improve performance compared with object-based implementations.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.