English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

In-depth Analysis of Generic Types in C#

The previous article introduced the analysis of the type system in C# (value types and reference types) to everyone. In this article, I will introduce the C# generic types to everyone.

Let's talk about generics in C#. Proficiently using generics can enhance the reusability of code, making our code instantly sophisticated, of course, only a little bit, really only a little bit, because there is still a lot of knowledge to learn and master later. Let's take a look at the next example using Dictionary<TKey, TValue>.

static void Main(string[] args)
{
 Dictionary<int, string> result = GetAll();
}
public static Dictionary<int, string> GetAll()
{
  var dic = new Dictionary<int, string>();
 dic.Add(1, "aaa");
 dic.Add(1, "aaa");
 dic.Add(1, "aaa");
 return dic;
}

  There are two forms of generics: generic types (classes, interfaces, delegates, and structures) and generic methods, like TKey and TValue are type parameters, and the int and string passed in are real types, which can be seen that type parameters are just placeholders for real types. A generic without providing real parameters is called an unconstructed generic type, and if type actual parameters are specified, it is called a constructed type, and the type instance is the object we use. The relationship diagram below.

  Judging generics can be a headache, and we will talk about it in detail next, maybe not very clear, do our best, because what I don't understand is also not very clear in the book, let's explain it here first. If you are not clear, you can see the explanation in the book. Let's see the picture below

  When looking at such generic methods, in actual use, you need to replace the parameter types inside (as mentioned before, the parameter type is actually a placeholder for type actual parameters), use string to replace T, and use int to replace TOutput  

 public static List<int> GetAll(Converter<string, int> conv)
 {
}

  Among them, Converter<string, int> is a constructed type, conv is a formal parameter, and now you should know the function of this generic method: use an instance of Converter<string, int> generic delegate as a parameter, and return a list containing integers.

The above-mentioned is the C# generic type introduced by the editor, hoping it will be helpful to everyone!