{"id":585,"date":"2022-05-01T15:56:26","date_gmt":"2022-05-01T08:56:26","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=585"},"modified":"2022-06-03T15:08:50","modified_gmt":"2022-06-03T08:08:50","slug":"csharp-generics","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-generics\/","title":{"rendered":"C# Generics"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about C# generics and how to define a generic method that works with any type.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the C# generics<\/h2>\n\n\n\n<p>C# generics allow you to write code that works with more than one type. By using generics, you can write code with placeholders for types and then provide the actual types when using the code.<\/p>\n\n\n\n<p>Suppose you need to write a method that swaps the values of two <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-integer\/\">integer<\/a> variables. To do that, you can define a method called <code>SwapInt()<\/code> that accepts two integer parameters like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">SwapInt<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">ref<\/span> <span class=\"hljs-keyword\">int<\/span> a, <span class=\"hljs-keyword\">ref<\/span> <span class=\"hljs-keyword\">int<\/span> b<\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">int<\/span> temp = a;\n        a = b;\n        b = temp;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Later, you want to swap the values of two <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-string\/\">string<\/a> variables. In this case, you need to define a new method that swaps the strings:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">SwapString<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">ref<\/span> <span class=\"hljs-keyword\">string<\/span> a, <span class=\"hljs-keyword\">ref<\/span> <span class=\"hljs-keyword\">string<\/span> b<\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">string<\/span> temp = a;\n           a = b;\n           b = temp;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Both <code>SwapInt()<\/code> and <code>SwapString()<\/code> methods have the same logic except for the types of the variables that they deal with.<\/p>\n\n\n\n<p>Imagine that you need to swap values of two variables of a new type e.g., <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-float\/\">float<\/a>, you need to define a new method for each new type. As the result, you&#8217;ll have lots of <code>Swap*<\/code> methods with the same logic. <\/p>\n\n\n\n<p>To resolve this, you can create a generic method that swaps values of variables of any type like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> Swap&lt;T&gt;(<span class=\"hljs-keyword\">ref<\/span> T a, <span class=\"hljs-keyword\">ref<\/span> T b)\n{\n    T temp = a;\n      a = b;\n      b = temp;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this <code>Swap()<\/code> method, instead of using a specific type, we use the placeholder T for the type. <\/p>\n\n\n\n<p class=\"note\">Note that the name of the placeholder <code>T<\/code> is a community convention. It means that you can use any string like A, B, TYPE, etc.<\/p>\n\n\n\n<p>When using the <code>Swap()<\/code> method, you can specify the specific type. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">int<\/span> x = <span class=\"hljs-number\">10<\/span>, y = <span class=\"hljs-number\">20<\/span>;\n\nSwap&lt;<span class=\"hljs-keyword\">int<\/span>&gt;(<span class=\"hljs-keyword\">ref<\/span> x, <span class=\"hljs-keyword\">ref<\/span> y);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, we specify the <code>int<\/code> type inside the angle brackets (<code>&lt;&gt;<\/code>) that follows the method name. Since the types of <code>x<\/code> and <code>y<\/code> are <code>int<\/code>, you can make the method call short like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">int<\/span> x = <span class=\"hljs-number\">10<\/span>, y = <span class=\"hljs-number\">20<\/span>;\n\nSwap(<span class=\"hljs-keyword\">ref<\/span> x, <span class=\"hljs-keyword\">ref<\/span> y);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The following program illustrates how to use the generic <code>Swap()<\/code> method and uses it to swap values of two integers and two string variables:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Program<\/span>\n{\n    <span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> Swap&lt;T&gt;(<span class=\"hljs-keyword\">ref<\/span> T a, <span class=\"hljs-keyword\">ref<\/span> T b)\n    {\n        T temp = a;\n        a = b;\n        b = temp;\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Main<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span>&#91;] args<\/span>)<\/span>\n    {\n        <span class=\"hljs-comment\">\/\/ swap integers<\/span>\n        <span class=\"hljs-keyword\">int<\/span> x = <span class=\"hljs-number\">10<\/span>, y = <span class=\"hljs-number\">20<\/span>;\n\n        Console.WriteLine(<span class=\"hljs-string\">$\"Before swapping: x=<span class=\"hljs-subst\">{x}<\/span>,y=<span class=\"hljs-subst\">{y}<\/span>\"<\/span>);\n        Swap(<span class=\"hljs-keyword\">ref<\/span> x, <span class=\"hljs-keyword\">ref<\/span> y);\n        Console.WriteLine(<span class=\"hljs-string\">$\"After swapping: x=<span class=\"hljs-subst\">{x}<\/span>,y=<span class=\"hljs-subst\">{y}<\/span>\"<\/span>);\n        \n        <span class=\"hljs-comment\">\/\/ swap strings<\/span>\n\n        <span class=\"hljs-keyword\">string<\/span> s1 = <span class=\"hljs-string\">\"hello\"<\/span>, s2 = <span class=\"hljs-string\">\"goodbye\"<\/span>;\n\n        Console.WriteLine(<span class=\"hljs-string\">$\"Before swapping: s1=<span class=\"hljs-subst\">{s1}<\/span>,s2=<span class=\"hljs-subst\">{s2}<\/span>\"<\/span>);\n        Swap(<span class=\"hljs-keyword\">ref<\/span> s1, <span class=\"hljs-keyword\">ref<\/span> s2);\n        Console.WriteLine(<span class=\"hljs-string\">$\"After swapping: s1=<span class=\"hljs-subst\">{s1}<\/span>,s2=<span class=\"hljs-subst\">{s2}<\/span>\"<\/span>);\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">Before swapping: x=10,y=20\nAfter swapping: x=20,y=10\nBefore swapping: s1=hello,s2=goodbye\nAfter swapping: s1=goodbye,s2=hello<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>C# allows you to use generics with the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-class\/\">Classes<\/a><\/li><li>Methods<\/li><li><a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-interface\/\">Interfaces<\/a><\/li><li><a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/c-delegate\/\">Delegates<\/a><\/li><li>Structs<\/li><\/ul>\n\n\n\n<p>In practice, you&#8217;ll find that generics are extensively used in the collection types like <code>List&lt;T&gt;<\/code>, <code>Stack&lt;T&gt;<\/code>, <code>Queue&lt;T&gt;<\/code>, etc. These are called <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/api\/system.collections.generic\" target=\"_blank\" rel=\"noreferrer noopener\">generic collection types<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>C# generics allow you to write general-purpose code that uses the same type in multiple places without knowing that type upfront.<\/li><li>Use C# generics to write reusable, type-neutral code.<\/li><\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"585\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-generics\/\"\n\t\t\t\tdata-post-title=\"C# Generics\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"585\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-generics\/\"\n\t\t\t\tdata-post-title=\"C# Generics\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about C# generics and how to define a generic method that works with any type.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":7,"menu_order":64,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-585","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/585","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/comments?post=585"}],"version-history":[{"count":4,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/585\/revisions"}],"predecessor-version":[{"id":619,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/585\/revisions\/619"}],"up":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/7"}],"wp:attachment":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/media?parent=585"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}