Home > Backend Development > C#.Net Tutorial > Explain how generics work in C#

Explain how generics work in C#

WBOY
Release: 2023-08-27 23:45:02
forward
1056 people have browsed it

解释泛型在 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!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template