Explain how generics work in 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
public class Locator<T> { }
To create an instance of Locator
var stringLocator = new Locator<string>();
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);
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 'string' to 'int' [c-sharp]csharp(CS0029) int item = stringLocator.Locate(2);
When inheriting from a generic base type or generic interface, the generic type can use type parameters as type arguments. The generic LinkedList
public class LinkedList<T> : IEnumerable<T>
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
public class Swapper{ public T Swap<T>(T first, T second){ T temp = first; first = second; second = temp; return temp; } }
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);
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>
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 li>
- 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; } }
Output
CSharp a = 3, b = 5
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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.

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

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

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

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,

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

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
