Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

C# Tutorial

C# HOME C# Intro C# Get Started C# Syntax C# Output C# Comments C# Variables C# Data Types C# Type Casting C# User Input C# Operators C# Math C# Strings C# Booleans C# If...Else C# Switch C# While Loop C# For Loop C# Break/Continue C# Arrays

C# Methods

C# Methods C# Method Parameters C# Method Overloading C# Scope C# Recursion

C# Classes

C# OOP C# Classes/Objects C# Class Members C# Constructors C# this Keyword C# Access Modifiers C# Properties C# Static C# Inheritance C# Polymorphism C# Abstraction C# Interface C# Enums C# Structs

C# Errors

C# Errors C# Debugging C# Exceptions

C# Data Structures

C# Data Structures C# List C# Dictionary C# HashSet C# Stack C# Queue

C# Advanced

C# Files C# Date and Time C# Nullable Types C# Generics C# Lambda C# LINQ

C# Cert

C# Certificate

C# How To

C# How Tos

C# Examples

C# Examples C# Compiler C# Exercises C# Quiz C# Practice Problems C# Server C# Syllabus C# Study Plan


C# Generics


Share

Generics

In the Method Overloading chapter, you learned that many methods can have the same name, with different parameter types.

Look at these two methods. They do the same thing, but one takes an int and the other takes a string:

Example

static void Print(int value)
{
  Console.WriteLine("Value: " + value);
}

static void Print(string value)
{
  Console.WriteLine("Value: " + value);
}

If you also need the method for double and bool, you must write two more copies of the same code.

Generics solve this problem. With generics, you write the method only once, and the type is decided when you use the method.


Generic Methods

To create a generic method, write <T> after the method name. T is a type parameter: a placeholder for a type (T is short for "type").

Then use T as the type of the parameter:

Example

static void Print<T>(T value)
{
  Console.WriteLine("Value: " + value);
}

static void Main(string[] args)
{
  Print(25);
  Print("Hello");
  Print(true);
}

Try it Yourself »

Example explained

  • When you call Print(25), T becomes int
  • When you call Print("Hello"), T becomes string
  • When you call Print(true), T becomes bool

C# looks at the value you send and chooses the type for you. You can also write the type yourself: Print<int>(25).

You can use T more than once in the method. Here, T[] is an array of any type, and the loop goes through it:

Example

static void PrintAll<T>(T[] items)
{
  foreach (T item in items)
  {
    Console.WriteLine(item);
  }
}

static void Main(string[] args)
{
  int[] numbers = {1, 2, 3};
  string[] cars = {"Volvo", "BMW", "Ford"};
  PrintAll(numbers);
  PrintAll(cars);
}

Try it Yourself »



Generic Classes

A class can also be generic. Write <T> after the class name, and use T inside the class.

This Box class can hold one value of any type:

Example

class Box<T>
{
  public T content;
}

class Program
{
  static void Main(string[] args)
  {
    Box<int> numberBox = new Box<int>();
    numberBox.content = 42;

    Box<string> textBox = new Box<string>();
    textBox.content = "Hello";

    Console.WriteLine(numberBox.content);
    Console.WriteLine(textBox.content);
  }
}

Try it Yourself »

When you create an object, write the type inside < >:

  • In Box<int>, T becomes int, so content is an int
  • In Box<string>, T becomes string, so content is a string

C# still checks the type. If you try to put a string into a Box<int>, you get an error before the program runs.


Generics You Already Know

The List and Dictionary classes are generic classes. Their full names are List<T> and Dictionary<TKey, TValue>:

Example

List<string> cars = new List<string>();  // T is string
List<int> scores = new List<int>();      // T is int

Dictionary<string, int> ages = new Dictionary<string, int>();  // TKey is string, TValue is int

That is why one List class can hold strings, numbers, or objects of your own classes.

A Dictionary has two type parameters: TKey is the type of the keys, and TValue is the type of the values.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.