{"id":61799,"date":"2022-01-05T08:00:00","date_gmt":"2022-01-05T07:00:00","guid":{"rendered":"https:\/\/drafts.code-maze.com\/?p=61799"},"modified":"2022-01-05T08:48:04","modified_gmt":"2022-01-05T07:48:04","slug":"csharp-polymorphism","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-polymorphism\/","title":{"rendered":"Polymorphism in C#"},"content":{"rendered":"<p>In this post, we are going to learn about the different types of polymorphism in C#, how they work and how we can use them in our code.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\"><span style=\"font-weight: 400;\">To download the source code for this article, you can visit our <\/span><a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/csharp-intermediate-topics\/PolymorphismInCsharp\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Let&#8217;s start.<\/p>\n<h2><a id=\"a1\"><\/a>Types of Polymorphism in C#<\/h2>\n<p>There are two types of polymorphism:<\/p>\n<ul>\n<li>Compile Time Polymorphism (method overloading)<\/li>\n<li>Run-Time Polymorphism (method overriding)<\/li>\n<\/ul>\n<p>Also, generic programming is sometimes referred to as another type of polymorphism (parametric polymorphism). That&#8217;s because a generic class can operate in a different way, depending on the classes we use as type parameters.<\/p>\n<p>You can find more about generic programming in our article about <a href=\"https:\/\/code-maze.com\/csharp-generics\/\" target=\"_blank\" rel=\"noopener\">C# Generics<\/a>.<\/p>\n<h2><a id=\"a2\"><\/a>Compile-Time Polymorphism<\/h2>\n<p><strong>Compile-time polymorphism in C# is the existence of multiple methods with the same name, but with different arguments in type and\/or number.<\/strong> We also call it method overloading. We can use it in situations where we need to implement multiple methods with similar functionality and we opt to give them the same name:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Logger\r\n{\r\n    private StreamWriter LogFile;\r\n    public Logger(StreamWriter logFile)\r\n    {\r\n        LogFile = logFile;\r\n    }\r\n\r\n    public void Log(string message, LogLevels level)\r\n    {\r\n        LogFile.Write(level + \" ---\");\r\n        LogFile.Write(DateTime.Now.ToString() + \" ---\");\r\n        LogFile.WriteLine(message);\r\n        LogFile.Flush();\r\n    }\r\n\r\n    public void Log(string message)\r\n    {\r\n        Log(message, LogLevels.Info);\r\n    }\r\n\r\n    public void Log(string message, int level)\r\n    {\r\n        if (Enum.IsDefined(typeof(LogLevels), level))\r\n        {\r\n            Log(message, (LogLevels)Enum.Parse(typeof(LogLevels), level.ToString()));\r\n        }\r\n        else\r\n        {\r\n            throw new Exception(\"Log level value does not exist\");\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p>In this example, class <code>Logger<\/code> defines 3 methods and makes use of a <code>LogLevels<\/code> enum:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public enum LogLevels\r\n{\r\n    Info = 1,\r\n    Warning = 2,\r\n    Error = 3\r\n}<\/pre>\n<p>The second method provides a default value (Info) for the log level. The third method accepts an integer as input and converts it to the corresponding log level. Both methods eventually use the first one, in order to write the message to the log file.<\/p>\n<p>A special case of method overloading is operator overloading. Here we can define multiple implementations for each operator method. Also, constructors are frequently overloaded; we can have constructors with multiple parameters as well as the default constructor.<\/p>\n<p>Another reason to use method overloading is when we need to change the definition of a method by adding one or more parameters to it. Since this change will probably break existing code, sometimes it is preferable to introduce a new method that will overload the initial one.<\/p>\n<h2><a id=\"a3\"><\/a>Run-Time Polymorphism<\/h2>\n<p>In the case of run-time polymorphism in C#, an object behaves in a different way depending on the context in which it is used.<\/p>\n<h3>How it works<\/h3>\n<p>To understand the concepts better, let&#8217;s define a good example that can help us.<\/p>\n<p>First, let&#8217;s create a <code>Package<\/code> class defines the common information necessary to deliver a package to its destination (recipient name and address). It also defines the characteristics of the package (weight and receipt date).<\/p>\n<p>The <code>Package<\/code> class also defines two methods: <code>GetDeliveryCost()<\/code> and <code>GetDeliveryDate()<\/code>. Those methods calculate the expected cost and delivery date of the package. We base the calculation on a package weight, and receipt date:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Package\r\n{\r\n    public string Recipient { get; set; }\r\n    public string Address { get; set; }\r\n    public decimal Weight { get; set; }\r\n    public DateTime SendDate { get; set; }\r\n\r\n    \/\/ ...\r\n\r\n    public decimal GetDeliveryCost()\r\n    {\r\n        return 3 * Weight;\r\n    }\r\n\r\n    public DateTime GetDeliveryDate()\r\n    {\r\n        if (SendDate.DayOfWeek == DayOfWeek.Friday)\r\n            return SendDate.AddDays(4);\r\n        if (SendDate.DayOfWeek == DayOfWeek.Thursday)\r\n            return SendDate.AddDays(4);\r\n        else\r\n            return SendDate.AddDays(2);\r\n    }\r\n}\r\n<\/pre>\n<p>We&#8217;re also going to add another class called <code>ExpeditedPackage<\/code> which inherits from the <code>Package<\/code> class.<\/p>\n<p>This class has a slightly different delivery cost and delivery date calculation:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class ExpeditedPackage : Package\r\n{\r\n    \/\/ ...\r\n\r\n    public new decimal GetDeliveryCost()\r\n    {\r\n        return 4 * Weight + 2;\r\n    }\r\n\r\n    public new DateTime GetDeliveryDate()\r\n    {\r\n        return SendDate.AddDays(1);\r\n    }\r\n}<\/pre>\n<p>And we&#8217;ll add another class called <code>InternationalPackage<\/code> which takes the destination country into account:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class InternationalPackage : Package\r\n{\r\n    public string CountryCode { get; set; }\r\n\r\n    \/\/ ...\r\n    public new decimal GetDeliveryCost()\r\n    {\r\n        if (CountryCode == \"US\")\r\n            return 6 * Weight + 3;\r\n        else if (CountryCode == \"UK\")\r\n            return 5 * Weight + 4;\r\n        else if (CountryCode == \"DE\")\r\n            return 6 * Weight;\r\n        else\r\n            return 6 * Weight + 2;\r\n    }\r\n\r\n    public new DateTime GetDeliveryDate()\r\n    {\r\n        if (CountryCode == \"US\")\r\n            return SendDate.AddDays(3);\r\n        else if (CountryCode == \"UK\")\r\n            return SendDate.AddDays(2);\r\n        else if (CountryCode == \"DE\")\r\n            return SendDate.AddDays(1);\r\n        else\r\n            return SendDate.AddDays(2);\r\n    }\r\n}<\/pre>\n<p>With polymorphism, we can have a base class reference point to an object of a subclass:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">ExpeditedPackage ep = new ExpeditedPackage(\"Sender B\", \"Address B\", 10, DateTime.Now);\r\nPackage p = ep;\r\n<\/pre>\n<p>Note that this operation is only possible due to the base class \u2013 subclass relationship between <code>Package<\/code> and <code>ExpeditedPackage<\/code>. It does not work the other way round:\u00a0 for instance, we cannot have an <code>ExpeditedPackage<\/code> reference pointing to a <code>Package<\/code> object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Package p = new Package(\"Sender A\", \"Address A\", 10, DateTime.Now);\r\nExpeditedPackage ep = p;  \/\/compiler error<\/pre>\n<p>Furthermore, it&#8217;s not possible for unrelated classes to point at each other:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Package p = new Package(\"Sender A\", \"Address A\", 10, DateTime.Now);\r\nPerson pr = p;  \/\/compiler error<\/pre>\n<p>Now, let&#8217;s try to call the <code>GetDeliveryCost()<\/code> method using the reference to the <code>ExpeditedPackage<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">ExpeditedPackage ep = new ExpeditedPackage(\"Sender B\", \"Address B\", 10, DateTime.Now);\r\nPackage p = ep;\r\nConsole.WriteLine(\"Cost: \" + p.GetDeliveryCost());<\/pre>\n<p>We can see that we actually call the method defined in the <code>Package<\/code> class. This happens because the reference of type <code>Package<\/code> knows only about the inner workings of the <code>Package<\/code> class. This behavior will change as soon as we introduce virtual methods into our classes.<\/p>\n<h3>Polymorphism with Virtual Methods<\/h3>\n<p>Now, let\u2019s insert the <code>virtual<\/code> keyword in the declaration of the two methods in the <code>Package<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"5,10\">public class Package\r\n{\r\n    \/\/ ...\r\n\r\n    public virtual decimal GetDeliveryCost()\r\n    {\r\n        return 3 * Weight;\r\n    }\r\n\r\n    public virtual DateTime GetDeliveryDate()\r\n    {\r\n        if (SendDate.DayOfWeek == DayOfWeek.Friday)\r\n            return SendDate.AddDays(4);\r\n        if (SendDate.DayOfWeek == DayOfWeek.Thursday)\r\n            return SendDate.AddDays(4);\r\n        else\r\n            return SendDate.AddDays(2);\r\n    }\r\n}\r\n<\/pre>\n<p>We need to mark the respective methods in the <code>ExpeditedPackage<\/code> class with the <code>override<\/code> keyword in order to make them override the logic of the <code>Package<\/code> base class methods:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"5,10\">public class ExpeditedPackage : Package\r\n{\r\n    \/\/ ...\r\n\r\n    public override decimal GetDeliveryCost()\r\n    {\r\n        return 4 * Weight + 2;\r\n    }\r\n\r\n    public override DateTime GetDeliveryDate()\r\n    {\r\n        return SendDate.AddDays(1);\r\n    }\r\n}<\/pre>\n<p>Now we get the expected delivery cost and date from the methods of the <code>ExpeditedPackage<\/code> class.<\/p>\n<p>The <code>virtual<\/code> keyword modifies the way the reference works. Now, we can call methods of the<code>ExpeditedPackage<\/code> subclass, through a reference of the base class type <code>Package<\/code>.<\/p>\n<h3>Polymorphism with Abstract Classes<\/h3>\n<p>We can also leverage the concept of <a href=\"https:\/\/code-maze.com\/csharp-abstract-classes\/\" target=\"_blank\" rel=\"noopener\">abstract classes<\/a> to make polymorphism work in our code. Let&#8217;s consider a variation of the packages hierarchy. Here we define an abstract base class <code>Package<\/code> that contains the necessary properties of the package. We also declare the two methods as abstract. This means that we cannot instantiate an object of the type <code>Package<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"1,5,7\">public abstract class Package\r\n{\r\n    \/\/ ...\r\n    \r\n    public abstract decimal GetDeliveryCost();\r\n\r\n    public abstract DateTime GetDeliveryDate();\r\n}<\/pre>\n<p>However, we can use <code>Package<\/code> as a base class to derive subclasses from. Now we move the functionality of the base package to a new subclass, <code>BasePackage<\/code> and we implement the two methods:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"5,10\">public class BasePackage: Package\r\n{\r\n    \/\/ ...\r\n    \r\n    public override decimal GetDeliveryCost()\r\n    {\r\n        return 3 * Weight;\r\n    }\r\n\r\n    public override DateTime GetDeliveryDate()\r\n    {\r\n        if (SendDate.DayOfWeek == DayOfWeek.Friday)\r\n            return SendDate.AddDays(4);\r\n        if (SendDate.DayOfWeek == DayOfWeek.Thursday)\r\n            return SendDate.AddDays(4);\r\n        else\r\n            return SendDate.AddDays(2);\r\n    }\r\n}<\/pre>\n<p>We can use this approach if there is no point in having concrete objects in the base class. We can also use it when we do not want to implement some of the methods of the base class and we decide to leave them abstract.<\/p>\n<p>Abstract classes bear similarity to interfaces, as we can use both concepts to make a group of classes provide the same functionality. However, there are some differences. <strong>The most important difference is the fact that a class can inherit only from one base class, but it can implement multiple interfaces.<\/strong><\/p>\n<h3>Sealed and New Keywords<\/h3>\n<p>When we declare a method as <code>virtual<\/code>, it remains <code>virtual<\/code> in all subclasses down the class hierarchy. This means that in a class that derives from <code>ExpeditedPackage<\/code> (e.g. <code>PremiumExpeditedPackage<\/code>) we can provide a new definition of both virtual methods. We can prevent this behavior by marking those methods as <code>sealed<\/code> in <code>ExpeditedPackage<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"5,10\">public class ExpeditedPackage : Package\r\n{\r\n    \/\/ ...\r\n\r\n    public sealed override decimal GetDeliveryCost()\r\n    {\r\n        return 4 * Weight + 2;\r\n    }\r\n\r\n    public sealed override DateTime GetDeliveryDate()\r\n    {\r\n        return SendDate.AddDays(1);\r\n    }\r\n}<\/pre>\n<p>If we try to override any of the methods in <code>PremiumExpeditedPackage<\/code>, we&#8217;ll get a compiler error. We can still provide new functionality to <code>PremiumExpeditedPackage<\/code> by using the keyword <code>new<\/code>to those methods:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"5,10\">public class PremiumExpeditedPackage : ExpeditedPackage\r\n{\r\n    \/\/ ...\r\n    \r\n    public new decimal GetDeliveryCost()\r\n    {\r\n        return 6 * Weight + 3;\r\n    }\r\n\r\n    public new DateTime GetDeliveryDate()\r\n    {\r\n        return SendDate;\r\n    }\r\n}<\/pre>\n<p>However, if we try to call those methods through a reference of type <code>Package<\/code>, we will see that we will actually call the sealed methods of <code>ExpeditedPackage<\/code>, since they are the last step in the chain of virtual methods in the hierarchy.<\/p>\n<h3>Access Base Class Members<\/h3>\n<p>If we need to, we can use the keyword <code>base<\/code> to get access to virtual members of the base class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"8\">public class InternationalPackage : Package\r\n{\r\n    \/\/ ...\r\n    \r\n    public override decimal GetDeliveryCost()\r\n    {\r\n        if (CountryCode == \"US\")\r\n            return base.GetDeliveryCost();\r\n        else if (CountryCode == \"UK\")\r\n            return 5 * Weight + 4;\r\n        else if (CountryCode == \"DE\")\r\n            return 6 * Weight;\r\n        else\r\n            return 6 * Weight + 2;\r\n    }\r\n    \r\n    \/\/ ...\r\n}<\/pre>\n<p>Here, we treat international packages sent to the US as simple packages, both in terms of cost and delivery date. We accomplish this by calling the respective methods of the base <code>Package<\/code>\u00a0class.<\/p>\n<h3>Things to Consider<\/h3>\n<p>For the run-time polymorphism concept to work, both methods, in the base class and the subclass, should have exactly the same signature with the exception of the return type.<\/p>\n<p>We can only access the properties and methods that are defined in the base class. For instance, we cannot access property <code>CountryCode<\/code> from <code>InternationalPackage<\/code>, as it is only defined in the subclass.<\/p>\n<h3>Where to Use Run-Time Polymorphism in C#<\/h3>\n<p>By using the run-time polymorphism we get many advantages. Let&#8217;s cover the most important ones with a practical example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"5,14,16,22\">public class CourierBranch\r\n{\r\n    public string Name { get; set; }\r\n    public string Address { get; set; }\r\n    public List&lt;Package&gt; packages { get; set; }\r\n\r\n    public CourierBranch(string name, string address)\r\n    {\r\n        Name = name;\r\n        Address = address;\r\n        packages = new List&lt;Package&gt;();\r\n    }\r\n\r\n    public void AddPackage(Package newPackage)\r\n    {\r\n        packages.Add(newPackage);\r\n    }\r\n\r\n    public decimal GetTotalCost()\r\n    {\r\n        decimal totalCost = 0;\r\n        foreach (var package in packages)\r\n        {\r\n            totalCost += package.GetDeliveryCost();\r\n        }\r\n        return totalCost;\r\n    }\r\n\r\n    public void PrintList()\r\n    {\r\n        foreach (var package in packages)\r\n        {\r\n            Console.WriteLine(\"Cost: \" + package.GetDeliveryCost());\r\n            Console.WriteLine(\"Delivery date: \" + package.GetDeliveryDate());\r\n        }\r\n    }\r\n}<\/pre>\n<p>Here we&#8217;ve implemented a new class <code>CourierBranch<\/code>\u00a0that abstracts the work of a local branch in a package courier company. Each branch maintains a list of all packages that it should deliver.<\/p>\n<p>In this example, we will add packages of all types for delivery and we will get the calculated costs and delivery dates for those packages:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">CourierBranch Branch1 = new CourierBranch(\"Branch 1\", \"12 Main str.\");\r\nBranch1.AddPackage(new Package(\"Sender A\", \"Address A\", 10, DateTime.Now));\r\nBranch1.AddPackage(new ExpeditedPackage(\"Sender B\", \"Address B\", 10, DateTime.Now));\r\nBranch1.AddPackage(new InternationalPackage(\"Sender C\", \"Address C\", 10, DateTime.Now, \"US\"));\r\nBranch1.PrintList();\r\n<\/pre>\n<h2>Benefits of Run-Time Polymorphism in C#<\/h2>\n<p>Run-time polymorphism is an extremely useful concept.\u00a0<\/p>\n<p><strong>We decouple our code. <\/strong>Consider the case where a new type of package is introduced sometime in the future. Note that the <code>CourierBranch<\/code> class handles only references to the <code>Package<\/code> class and not to any of its subclasses. Therefore, there will be no need to modify it to handle a new type of package. This way, the <code>CourierBranch<\/code> class is decoupled from the specifics of packages and thus makes our code more maintainable.<\/p>\n<p><strong>We can store multiple types of objects in one common list. <\/strong>Without polymorphism, we would have to maintain a separate list for each type of <code>Package<\/code> we use. With the use of polymorphism, we can store all package types in the same list and we can handle them in a similar fashion. Also, the definition of a new package type will have no effect on this class. We won&#8217;t have to add yet another list for the new package type.<\/p>\n<p><strong>We can pass multiple types of objects in the same method. <\/strong>The <code>AddPackage()<\/code> method can take all types of packages as input arguments. To achieve this, we&#8217;ve defined the input of this method to be of the <code>Package<\/code> base type. In the absence of run-time polymorphism, we would have to define three <code>AddPackage()<\/code> methods, one for each type of package available. Furthermore, we would have to modify the <code>CourierBranch<\/code> class and add another <code>AddPackage()<\/code> method, in the case of a new package offering.<\/p>\n<p><strong>We avoid the use of switch\/case (or if\/else) blocks and the <\/strong><code>typeof<\/code><strong> operator. <\/strong>Without the run-time polymorphism, we would have to use a simple <code>Package<\/code> class. This class would contain a member variable <code>Type<\/code> describing the type of the package. In this case, we would have to maintain an if-else block for the calculation of the delivery date and cost. The introduction of a new type of package would require the modification of the <code>Package<\/code> class. This may also affect other places in our code that depend on this class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Package\r\n{\r\n    public string Type { get; set; }\r\n    public string Recipient { get; set; }\r\n    public string Address { get; set; }\r\n    public decimal Weight { get; set; }\r\n    public DateTime SendDate { get; set; }\r\n    public string CountryCode { get; set; }\r\n\r\n    \/\/ ...\r\n\r\n    public decimal GetDeliveryCost()\r\n    {\r\n        if (Type == \"Expedited\")\r\n            return 4 * Weight + 2;\r\n        if (Type == \"International\")\r\n        {\r\n            if (CountryCode == \"US\")\r\n                return 6 * Weight + 3;\r\n            else if (CountryCode == \"UK\")\r\n                return 5 * Weight + 4;\r\n            else if (CountryCode == \"DE\")\r\n                return 6 * Weight;\r\n            else\r\n                return 6 * Weight + 2;\r\n        }\r\n        else\r\n            return 3 * Weight;\r\n    }\r\n\r\n    \/\/ ...\r\n}<\/pre>\n<p>Okay, that&#8217;s it for this lengthy but extremely important topic.<\/p>\n<h2><a id=\"a4\"><\/a>Conclusion<\/h2>\n<p>In this article, we have learned about the two types of polymorphism (compile-time and run-time) and we have seen ways to use this concept in our code.<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this post, we are going to learn about the different types of polymorphism in C#, how they work and how we can use them in our code. Let&#8217;s start. Types of Polymorphism in C# There are two types of polymorphism: Compile Time Polymorphism (method overloading) Run-Time Polymorphism (method overriding) Also, generic programming is sometimes [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12,506],"tags":[991,992,441,990],"class_list":["post-61799","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","category-intermediate","tag-intermediate","tag-oop","tag-polymorphism","tag-virtual-methods","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Polymorphism in C# - Code Maze<\/title>\n<meta name=\"description\" content=\"In this post, we learn about the concept of Polymorphism in C# and its two types: Compile-type and run-time polymorphism\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-polymorphism\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Polymorphism in C# - Code Maze\" \/>\n<meta property=\"og:description\" content=\"In this post, we learn about the concept of Polymorphism in C# and its two types: Compile-type and run-time polymorphism\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-polymorphism\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2022-01-05T07:00:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-01-05T07:48:04+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-polymorphism\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-polymorphism\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"Polymorphism in C#\",\"datePublished\":\"2022-01-05T07:00:00+00:00\",\"dateModified\":\"2022-01-05T07:48:04+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-polymorphism\/\"},\"wordCount\":1551,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-polymorphism\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"intermediate\",\"OOP\",\"Polymorphism\",\"virtual methods\"],\"articleSection\":[\"C#\",\"Intermediate\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-polymorphism\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-polymorphism\/\",\"url\":\"https:\/\/code-maze.com\/csharp-polymorphism\/\",\"name\":\"Polymorphism in C# - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-polymorphism\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-polymorphism\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2022-01-05T07:00:00+00:00\",\"dateModified\":\"2022-01-05T07:48:04+00:00\",\"description\":\"In this post, we learn about the concept of Polymorphism in C# and its two types: Compile-type and run-time polymorphism\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-polymorphism\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-polymorphism\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-polymorphism\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-polymorphism\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Polymorphism in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Polymorphism in C# - Code Maze","description":"In this post, we learn about the concept of Polymorphism in C# and its two types: Compile-type and run-time polymorphism","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-polymorphism\/","og_locale":"en_US","og_type":"article","og_title":"Polymorphism in C# - Code Maze","og_description":"In this post, we learn about the concept of Polymorphism in C# and its two types: Compile-type and run-time polymorphism","og_url":"https:\/\/code-maze.com\/csharp-polymorphism\/","og_site_name":"Code Maze","article_published_time":"2022-01-05T07:00:00+00:00","article_modified_time":"2022-01-05T07:48:04+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-polymorphism\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-polymorphism\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"Polymorphism in C#","datePublished":"2022-01-05T07:00:00+00:00","dateModified":"2022-01-05T07:48:04+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-polymorphism\/"},"wordCount":1551,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-polymorphism\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["intermediate","OOP","Polymorphism","virtual methods"],"articleSection":["C#","Intermediate"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-polymorphism\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-polymorphism\/","url":"https:\/\/code-maze.com\/csharp-polymorphism\/","name":"Polymorphism in C# - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-polymorphism\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-polymorphism\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2022-01-05T07:00:00+00:00","dateModified":"2022-01-05T07:48:04+00:00","description":"In this post, we learn about the concept of Polymorphism in C# and its two types: Compile-type and run-time polymorphism","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-polymorphism\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-polymorphism\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-polymorphism\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-polymorphism\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"Polymorphism in C#"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/61799","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=61799"}],"version-history":[{"count":7,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/61799\/revisions"}],"predecessor-version":[{"id":63025,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/61799\/revisions\/63025"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=61799"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=61799"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=61799"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}