Table of Contents
Generic types
Generic methods
Example
Output
Home Backend Development C#.Net Tutorial Explain how generics work in C#

Explain how generics work in C#

Aug 27, 2023 pm 11:45 PM

解释泛型在 C# 中的工作原理

Generics were added in C# version 2.0 and are one of the most important concepts in the language. They enable you to write reusable, high-performance code that is type-safe at compile time. Generics allow you to use a type in your code without knowing the type beforehand.

Generics are used in many places in .NET, including collections, delegates, and asynchronous code. With generics, you don't need to know the size of the collection in advance, and you can use generics with any element type, even custom data types specific to your code. C# provides support for generic types (classes, interfaces, etc.) and generic methods.

In generics, you have type parameters and type parameters. This is similar to a method that has parameters that you can pass to the method.

Generic types

The syntax for declaring a generic type consists of type parameters enclosed in angle brackets. The name of the type. For example, Locator is the generic class in the example below.

public class Locator<T>
{

}
Copy after login

To create an instance of Locator, use the new keyword followed by the name of the class. However, you can specify the actual type to be passed as parameter instead of T. The following example passes a string type as a parameter.

var stringLocator = new Locator<string>();
Copy after login

You can use type parameters (T) on class methods as shown in the following example.

public class Locator{
   public IList Items { get; set; }

      public T Locate(int index){
      return Items[index];
   }
}
var stringLocator = new Locator<string>();
string item = stringLocator.Locate(2);
Copy after login

Another benefit of generics is the IntelliSense provided by the editor. When you type stringLocator.Locate(4) in Visual Studio or VS Code and hover over the method name; it shows that it returns a string instead of a T. The compiler will throw an error if you try to assign the result to any type other than string. For example,

// Error: Cannot implicitly convert type &#39;string&#39; to &#39;int&#39; [c-sharp]csharp(CS0029)
int item = stringLocator.Locate(2);
Copy after login

When inheriting from a generic base type or generic interface, the generic type can use type parameters as type arguments. The generic LinkedList type implements the generic IEnumerable interface as well as other interfaces.

public class LinkedList<T> : IEnumerable<T>
Copy after login

Generic methods

A generic method is simply a method that declares a type parameter that you can use inside a method and use it as parameter and return type. In the following example, Swap is a generic method that takes two parameters of type T and returns an instance of T.

public class Swapper{
   public T Swap<T>(T first, T second){
      T temp = first;
      first = second;
      second = temp;
      return temp;
   }
}
Copy after login

Like generic types, when you call a generic method, it returns a strongly typed variable.

var swapper = new Swapper();
int result = swapper.Swap<int>(5, 3);
Copy after login

Can have multiple common parameters. The Dictionary class in the System.Collections.Generic namespace has two type parameters, key and value.

public class Dictionary<TKey, TValue>
Copy after login

Finally, it’s important to understand what is universal. For types, everything can be generic except enumerations. These include -

  • Class
  • Structure
  • Interface
  • Delegate

For type members, only methods and Nested types can be generic. The following members cannot be general -

  • Fields
  • Properties
  • Indexer
  • Constructor
  • Event
  • Terminator

Example

Live demonstration

using System;
using System.Collections.Generic;
class Program{
   static void Main(){
      var stringLocator = new Locator<string>(){
         Items = new string[] { "JavaScript", "CSharp", "Golang" }
      };
      string item = stringLocator.Locate(1);
      Console.WriteLine(item); // CSharp
      var swapper = new Swapper();
      int a = 5, b = 3;
      int result = swapper.Swap<int>(ref a, ref b);
      Console.WriteLine($"a = {a}, b = {b}");
   }
}
public class Locator<T>{
   public IList<T> Items { get; set; }
   public T Locate(int index){
      return Items[index];
   }
}
public class Swapper{
   public T Swap<T>(ref T first, ref T second){
      T temp = first;
      first = second;
      second = temp;
      return temp;
   }
}
Copy after login

Output

CSharp
a = 3, b = 5
Copy after login

The above is the detailed content of Explain how generics work in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the alternatives to NULL in C language What are the alternatives to NULL in C language Mar 03, 2025 pm 05:37 PM

This article explores the challenges of NULL pointer dereferences in C. It argues that the problem isn't NULL itself, but its misuse. The article details best practices for preventing dereferences, including pre-dereference checks, pointer initiali

How to add next-level C compiler How to add next-level C compiler Mar 03, 2025 pm 05:44 PM

This article explains how to create newline characters in C using the \n escape sequence within printf and puts functions. It details the functionality and provides code examples demonstrating its use for line breaks in output.

Which C language compiler is better? Which C language compiler is better? Mar 03, 2025 pm 05:39 PM

This article guides beginners on choosing a C compiler. It argues that GCC, due to its ease of use, wide availability, and extensive resources, is best for beginners. However, it also compares GCC, Clang, MSVC, and TCC, highlighting their differenc

Is NULL still important in modern programming in C language? Is NULL still important in modern programming in C language? Mar 03, 2025 pm 05:35 PM

This article emphasizes the continued importance of NULL in modern C programming. Despite advancements, NULL remains crucial for explicit pointer management, preventing segmentation faults by marking the absence of a valid memory address. Best prac

What are the web versions of C language compilers? What are the web versions of C language compilers? Mar 03, 2025 pm 05:42 PM

This article reviews online C compilers for beginners, focusing on ease of use and debugging capabilities. OnlineGDB and Repl.it are highlighted for their user-friendly interfaces and helpful debugging tools. Other options like Programiz and Compil

C language online programming website C language compiler official website summary C language online programming website C language compiler official website summary Mar 03, 2025 pm 05:41 PM

This article compares online C programming platforms, highlighting differences in features like debugging tools, IDE functionality, standard compliance, and memory/execution limits. It argues that the "best" platform depends on user needs,

Method of copying code by C language compiler Method of copying code by C language compiler Mar 03, 2025 pm 05:43 PM

This article discusses efficient code copying in C IDEs. It emphasizes that copying is an IDE function, not a compiler feature, and details strategies for improved efficiency, including using IDE selection tools, code folding, search/replace, templa

How to solve the problem of not popping up the output window by the C language compiler How to solve the problem of not popping up the output window by the C language compiler Mar 03, 2025 pm 05:40 PM

This article troubleshoots missing output windows in C program compilation. It examines causes like failing to run the executable, program errors, incorrect compiler settings, background processes, and rapid program termination. Solutions involve ch

See all articles