{"id":412,"date":"2022-01-06T15:27:02","date_gmt":"2022-01-06T08:27:02","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=412"},"modified":"2022-06-03T15:03:59","modified_gmt":"2022-06-03T08:03:59","slug":"csharp-casting","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-casting\/","title":{"rendered":"C# Casting"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about the C# casting including upcasting and downcasting.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to C# casting<\/h2>\n\n\n\n<p>C# is a statically-typed programming language. It means that after you declare a <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-variables\/\">variable<\/a>, you cannot redeclare it. Also, you cannot reassign a value of another type to the variable unless that type is implicitly compatible with the variable&#8217;s type.<\/p>\n\n\n\n<p>An object reference can be:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Implicitly upcast to a base class reference. An upcast always succeeds.<\/li><li>Explicitly downcast to a subclass reference. A downcast only succeeds if the objects are compatible types.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Upcasting<\/h3>\n\n\n\n<p>An upcast creates a base class reference from a subclass reference. For example:<\/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-keyword\">class<\/span> <span class=\"hljs-title\">Person<\/span>\n{\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">string<\/span> Name { <span class=\"hljs-keyword\">get<\/span>; <span class=\"hljs-keyword\">set<\/span>; }\n}\n\n<span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Employee<\/span>: <span class=\"hljs-title\">Person<\/span>\n{\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">string<\/span> JobTitle { <span class=\"hljs-keyword\">get<\/span>; <span class=\"hljs-keyword\">set<\/span>; }\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<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-keyword\">var<\/span> employee = <span class=\"hljs-keyword\">new<\/span> Employee()\n{\n    Name = <span class=\"hljs-string\">\"John Doe\"<\/span>,\n    JobTitle = <span class=\"hljs-string\">\"C# Developer\"<\/span>\n};\n\nPerson person = employee;<\/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>In this example:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>First, define the <code>Employee<\/code> class that <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-inheritance\/\">inherits<\/a> from the <code>Person<\/code> class. The <code>Person<\/code> class is a base class and the <code>Employee<\/code> class is a subclass.<\/li><li>Second, create a new instance of the <code>Employee<\/code> class and assign it to the <code>employee<\/code> variable.<\/li><li>Third, assign the object referenced by the <code>employee<\/code> variable to a reference of the <code>Person<\/code> class.<\/li><\/ul>\n\n\n\n<p>After upcasting, the variable <code>person<\/code> still references the same <code>Employee<\/code>&#8216;s object. Both <code>employee<\/code> and <code>person<\/code> variable reference the same <code>Employee<\/code>&#8216;s object. The object itself does not change.<\/p>\n\n\n\n<p>Although the <code>person<\/code> and <code>employee<\/code> variables refer to the same object, the <code>person<\/code> has a more restrictive view on that object. For example, it can only access the <code>Name<\/code> property but cannot access the <code>JobTitle<\/code> property of the object.<\/p>\n\n\n\n<p>The following statement will cause a compile-time error:<\/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\">person.JobTitle;<\/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>Error:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">'Person' does not contain a definition for 'JobTitle'...<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><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<h3 class=\"wp-block-heading\">Downcasting<\/h3>\n\n\n\n<p>A downcast operation creates a subclass reference from a base class reference. A downcast requires a cast expression with the following syntax:<\/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\">(T)E<\/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 cast expression explicitly converts the result of the expression (<code>E<\/code>) to the type <code>T<\/code>. If no explicit conversion exists from the type of <code>E<\/code> to type <code>T<\/code>, the compiler will raise an error.<\/p>\n\n\n\n<p>Also, at runtime, the explicit conversion might fail and the cast expression might throw an exception.<\/p>\n\n\n\n<p>The following example illustrates the downcasting:<\/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\">var<\/span> employee = <span class=\"hljs-keyword\">new<\/span> Employee()\n{\n    Name = <span class=\"hljs-string\">\"John Doe\"<\/span>,\n    JobTitle = <span class=\"hljs-string\">\"C# Developer\"<\/span>\n};\n\nPerson person = employee; <span class=\"hljs-comment\">\/\/ upcast<\/span>\n\nEmployee employee2 = (Employee)person; <span class=\"hljs-comment\">\/\/ downcast<\/span>\n\nConsole.WriteLine(employee2.Name);\nConsole.WriteLine(employee2.JobTitle);<\/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>In this example, the downcast operation explicitly converts the object referenced by the <code>person<\/code> reference to the <code>employee2<\/code>.<\/p>\n\n\n\n<p>Since the <code>employee2<\/code> variable refers to the <code>Employee<\/code> object, it can access all properties of the <code>Employee<\/code>&#8216;s object.<\/p>\n\n\n\n<p>The following defines the <code>Candidate<\/code> class that inherits from the <code>Person<\/code> class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" 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\">Person<\/span>\n{\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">string<\/span> Name { <span class=\"hljs-keyword\">get<\/span>; <span class=\"hljs-keyword\">set<\/span>; }\n}\n\n<span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Employee<\/span> : <span class=\"hljs-title\">Person<\/span>\n{\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">string<\/span> JobTitle { <span class=\"hljs-keyword\">get<\/span>; <span class=\"hljs-keyword\">set<\/span>; }\n}\n\n<span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Candidate<\/span> : <span class=\"hljs-title\">Person<\/span>\n{\n\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><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 downcast will fail at runtime:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">var<\/span> employee = <span class=\"hljs-keyword\">new<\/span> Employee()\n{\n    Name     = <span class=\"hljs-string\">\"John Doe\"<\/span>,\n    JobTitle = <span class=\"hljs-string\">\"C# Developer\"<\/span>\n};\n\nPerson person = employee;                <span class=\"hljs-comment\">\/\/ upcast<\/span>\nCandidate candidate = (Candidate)person; <span class=\"hljs-comment\">\/\/ downcast fail at runtime<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><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, the <code>person<\/code> variable references an instance of the <code>Employee<\/code> class. However, we cast it as an instance fo the <code>Candidate<\/code> class, which is not an instance of the <code>Employee<\/code> class.<\/p>\n\n\n\n<p>If you run the program, you&#8217;ll get the following exception:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">System.InvalidCastException: 'Unable to cast object of type 'Employee' to type 'Candidate'.'<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><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<h3 class=\"wp-block-heading\">The as operator<\/h3>\n\n\n\n<p>If a downcast fails, it&#8217;ll throw an exception at runtime. If you don&#8217;t want this behavior, you can use the <code>as<\/code> operator.<\/p>\n\n\n\n<p>The <code>as<\/code> operator performs a downcast that evaluates to <code>null<\/code> rather than throwing an exception if the downcast fails. This allows you to subsequentially check whether the result of the downcast is null or not. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">var<\/span> employee = <span class=\"hljs-keyword\">new<\/span> Employee()\n{\n    Name = <span class=\"hljs-string\">\"John Doe\"<\/span>,\n    JobTitle = <span class=\"hljs-string\">\"C# Developer\"<\/span>\n};\n\nPerson person = employee;<span class=\"hljs-comment\">\/\/ upcast<\/span>\n\nCandidate candidate = person <span class=\"hljs-keyword\">as<\/span> Candidate;\n<span class=\"hljs-keyword\">if<\/span> (candidate != <span class=\"hljs-literal\">null<\/span>)\n{\n    Console.WriteLine(candidate.Name);\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><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, the downcast fails. Therefore, the <code>candidate<\/code> variable is null. Then, we check whether the <code>candidate<\/code> is null or not before displaying its <code>name<\/code> property to the console.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>An object reference can be implicitly upcast to a base class reference. An upcast always succeeds.<\/li><li>An object reference can also be explicitly downcast to a subclass reference. A downcast succeeds only if the object is compatible typed.<\/li><li>Use the <code>as<\/code> operator to perform a downcast that evaluates to <code>null<\/code> rather than throwing an exception.<\/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=\"412\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-casting\/\"\n\t\t\t\tdata-post-title=\"C# Casting\"\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=\"412\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-casting\/\"\n\t\t\t\tdata-post-title=\"C# Casting\"\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 the C# casting including upcasting and downcasting.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":7,"menu_order":46,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-412","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/412","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=412"}],"version-history":[{"count":5,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/412\/revisions"}],"predecessor-version":[{"id":722,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/412\/revisions\/722"}],"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=412"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}