SlideShare a Scribd company logo
Inheritance & Polymorphism
Eng Teong Cheah
Microsoft MVP Windows Development
Inheritance
Inheritance
C# is an object oriented programming language so it supports one key feature of OOPS;
Inheritance.
In general, Inheritance can be explained as acquiring the properties of the parent.
For this, we will use the most common example of the car class.
You can see Car is an Object who has basic feature like name, height, no of wheels. It has two
specialized version one is sedan and other is hatchback. Both sedan and hatch back has all the
basic feature of car and some specialized property of their own. This feature is known as
inheritance.
Inheritance
When a child class has all the features
of base class plus its own specialized
properties. Then this phenomenon is
known as inheritance.
Inheritance
Types of inheritance supported by C# are follows:
- Single inheritance
Single base class and single derived class.
- Multilevel inheritance
B derive from A and C derive from B.
- Hierarchical inheritance
B and C both derived from A.
- Multiple inheritance using Interfaces
Class D derived from Interface A, Interface B and Class C.
Inheritance
Preventing a Class from Being Inherited C#
We can prevent the class from Being Inherited by Other Class by putting Sealed Keyword in class.
See Example Below:-
sealed class stringHandler
{
public string inputString { get; set; }
public string OutputString { get; set; }
public stringHandler(string inputstring)
{
this.inputString = inputString;
}
public String FormatString()
{
// Some Code here
}
}
Inheritance
Constructor initialization C# Inheritance
See the car example on top of this page, if we create an object of HatchBack class . The
constructor initialization series is given below –
HatchBack hb = new HatchBack("hatchback",4,125,40,true);
1. First Car constructor is initialized
public Car(string name, int wheelcount, float length, float
breadth)
{
this.Name = name;
this.WheelCount = wheelcount;
this.length = length;
this.breadth = breadth;
}
Inheritance
2. Second Hatchback Constructor will be initialized
public HatchBack(string name, int wheelcount, float length,
float breadth, bool isconvertible) : base(name, wheelcount,
length, breadth)
{
this.IsConvertible = isconvertible;
}
So, from these examples we can say that constructor initialization in inheritance will always follow
from base to derived downwards.
Inheritance
Calling Base class’s Constructor in Inherited C#
Classes :
Base class constructor is called in derived class using
base Keyword. See Car example on top of the
page Calling a Base class’s Hidden members in
inherited class C# :
Base class hidden member function can be called by
using base.functionname syntax.
See Example below -
Inheritance
Type Casting in Inheritance C#
Parent class reference can hold child class reference but
opposite is not true. Casting an object to a parent class
is called upcasting. Casting an object to child class is
called downcasting.
See Example below -
We have Draw() method both in base class and derived
class. But the see which one is called when.
If the Shape class’s Draw() Method is declared as virtual
and overridden in Oval class’s Draw() method then result
would be different. Result would be.
Output when Draw() method will be declared as Virtual
and overridden in derived class :
Shape Drawn
Oval Drawn
Oval Drawn
Polymorphism
Polymorphism
Polymorphism is one of the key features of OOPS. Polymorphism can be broken as below.
Polymorphism =Poly + morphism =Multiple + forms.
Polymorphism is simply calling derived class methods from base class reference during runtime. It
is the behavioural change of methods depending upon the instance called at runtime.
Polymorphism
Before we understand it in polymorphism in C# language, let’s understand it with a simple fantasy
example.
A mermaid, yes a mermaid. Viola……But how a mermaid is related to Polymorphism see image
below.
Mermaid shows a polymorphic
behavior according to
environment.
Mermaid behaves like human
while on earth and as a fish
while in water.
Example Class Hierarchy
Let's assume the following simple class hierarchy with classes A, B and C for the discussions in this
text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the
easier examples, we will only refer to a part of this class hierarchy.
Inherited Methods
A method Foo() which is declared in the base class A and not redeclared in classes B or C is
inherited in the two subclasses
Inherited Methods
The method Foo() can be overridden in classes B and C:
Inherited Methods
There are two problems with this code.
- The output is not really what we, say from Java, expected. The method Foo() is a non-virtual
method. C# requires the use of the keyword virtual in order for a method to actually be virtual. An
example using virtual methods and polymorphism will be given in the next section.
- Although the code compiles and runs, the compiler produces a warning:
...polymorphism.cs(11,15): warning CS0108: The keyword new is required on
'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'
This issue will be discussed in section Hiding and Overriding Methods.
Virtual and Overridden Methods
Only if a method is declared virtual, derived classes can override this method if they are explicitly
declared to override the virtual base class method with the override keyword.
Method Hiding
Why did the compiler in the second listing generate a warning? Because C# not only supports
method overriding, but also method hiding. Simply put, if a method is not overriding the derived
method, it is hiding it. A hiding method has to be declared using the new keyword. The correct
class definition in the second listing is thus:
Combining Method Overriding and Hiding
Methods of a derived class can both be virtual and at the same time hide the derived method. In
order to declare such a method, both keywords virtual and new have to be used in the method
declaration:
Combining Method Overriding and Hiding
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
Demo
Resources
• MSDN
• Techoschool

More Related Content

What's hot (20)

PPSX
Adaptation in animals
K G MALLIKARJAN
 
PDF
grain and feed ingredient storage molds & mycotoxins-campabadal
AbdelRahman Yousef
 
PPTX
Biodiversity and Evolution.pptx
RandyBaquiran1
 
PPT
The CD300 molecules: an emerging family of regulators of the Immune System
Vall d'Hebron Institute of Research (VHIR)
 
PPT
Aquatic biome
Denni Domingo
 
PPT
Dynamic ecosystems - Population Sampling
RichardBader
 
PPTX
Inbreeding
Md. Abu Bakar Siddik
 
PPS
Intro to ruminant digestion
Dr Neo
 
PPT
Community Ecology
Jenny Klemme
 
PDF
Breeds of swine
Margie Lumanggaya
 
PDF
poultry-production-management-module-final (1).pdf
JhonAdrianVargas
 
PPTX
Poultry Digestive system
UCV&AS IUB
 
PPTX
Presentation on Heritability
Santosh pathak
 
PPT
Animal nutrition
frit0087
 
PPTX
Measuring Biodiversity
Hawkesdale P12 College
 
PDF
biodiversity-131107231347-phpapp02.pdf
WarongWonglangka
 
PPT
Poultry Feed formulation
DrChandrasekarSeeniv
 
PPT
Introduction to biological molecules
stvb2170
 
PPS
Natural selection
Mahesh Rathva
 
Adaptation in animals
K G MALLIKARJAN
 
grain and feed ingredient storage molds & mycotoxins-campabadal
AbdelRahman Yousef
 
Biodiversity and Evolution.pptx
RandyBaquiran1
 
The CD300 molecules: an emerging family of regulators of the Immune System
Vall d'Hebron Institute of Research (VHIR)
 
Aquatic biome
Denni Domingo
 
Dynamic ecosystems - Population Sampling
RichardBader
 
Intro to ruminant digestion
Dr Neo
 
Community Ecology
Jenny Klemme
 
Breeds of swine
Margie Lumanggaya
 
poultry-production-management-module-final (1).pdf
JhonAdrianVargas
 
Poultry Digestive system
UCV&AS IUB
 
Presentation on Heritability
Santosh pathak
 
Animal nutrition
frit0087
 
Measuring Biodiversity
Hawkesdale P12 College
 
biodiversity-131107231347-phpapp02.pdf
WarongWonglangka
 
Poultry Feed formulation
DrChandrasekarSeeniv
 
Introduction to biological molecules
stvb2170
 
Natural selection
Mahesh Rathva
 

Viewers also liked (18)

PPTX
C# basics training (Inheritance)
Ankit Kashyap
 
PPTX
Inheritance in C#
Gautham Kuragayala K
 
PPTX
Inheritance
Sapna Sharma
 
PPT
Classes2
phanleson
 
PDF
Xamarin: Namespace and Classes
Eng Teong Cheah
 
PDF
Xamarin: Branching and Looping
Eng Teong Cheah
 
PPTX
Introduction of C#
Eng Teong Cheah
 
PDF
Xamarin: C# Methods
Eng Teong Cheah
 
PPT
Csharp4 inheritance
Abed Bukhari
 
PPTX
interface in c#
Deepti Pillai
 
PPT
Inheritance C#
Raghuveer Guthikonda
 
PPT
C#.NET
gurchet
 
PDF
Learn C# Programming - Data Types & Type Conversion
Eng Teong Cheah
 
PPTX
Inheritance in oops
Hirra Sultan
 
PPSX
Inheritance
Selvin Josy Bai Somu
 
PDF
Chapter 7 - Data Link Control Protocols 9e
adpeer
 
PPTX
Xamarin - First Application
Eng Teong Cheah
 
PDF
Learn C# programming - Program Structure & Basic Syntax
Eng Teong Cheah
 
C# basics training (Inheritance)
Ankit Kashyap
 
Inheritance in C#
Gautham Kuragayala K
 
Inheritance
Sapna Sharma
 
Classes2
phanleson
 
Xamarin: Namespace and Classes
Eng Teong Cheah
 
Xamarin: Branching and Looping
Eng Teong Cheah
 
Introduction of C#
Eng Teong Cheah
 
Xamarin: C# Methods
Eng Teong Cheah
 
Csharp4 inheritance
Abed Bukhari
 
interface in c#
Deepti Pillai
 
Inheritance C#
Raghuveer Guthikonda
 
C#.NET
gurchet
 
Learn C# Programming - Data Types & Type Conversion
Eng Teong Cheah
 
Inheritance in oops
Hirra Sultan
 
Chapter 7 - Data Link Control Protocols 9e
adpeer
 
Xamarin - First Application
Eng Teong Cheah
 
Learn C# programming - Program Structure & Basic Syntax
Eng Teong Cheah
 
Ad

Similar to Xamarin: Inheritance and Polymorphism (20)

PDF
Object oriented programming inheritance
Renas Rekany
 
PPTX
CSharp_03_Inheritance_introduction_with_examples
Ranjithsingh20
 
PPT
Opps
Lalit Kale
 
PPT
Visula C# Programming Lecture 7
Abou Bakr Ashraf
 
PPTX
Inheritance.pptx
PRIYACHAURASIYA25
 
PDF
7 inheritance and polymorphism
Tuan Ngo
 
DOCX
Ganesh groups
Ganesh Amirineni
 
PDF
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Akhil Mittal
 
PPT
Inheritance
abhay singh
 
PPT
20. Object-Oriented Programming Fundamental Principles
Intro C# Book
 
PDF
Net Interview-Questions 1 - 16.pdf
PavanNarne1
 
PPT
20 Object-oriented programming principles
maznabili
 
PPTX
29csharp
Sireesh K
 
PPTX
29c
Sireesh K
 
DOCX
C# Unit 2 notes
Sudarshan Dhondaley
 
PDF
(5) c sharp introduction_object_orientation_part_ii
Nico Ludwig
 
PPTX
Polymorphism in C# Function overloading in C#
Abid Kohistani
 
PPTX
Object oriented programming Fundamental Concepts
Bharat Kalia
 
PPTX
SAD04 - Inheritance
Michael Heron
 
Object oriented programming inheritance
Renas Rekany
 
CSharp_03_Inheritance_introduction_with_examples
Ranjithsingh20
 
Visula C# Programming Lecture 7
Abou Bakr Ashraf
 
Inheritance.pptx
PRIYACHAURASIYA25
 
7 inheritance and polymorphism
Tuan Ngo
 
Ganesh groups
Ganesh Amirineni
 
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Akhil Mittal
 
Inheritance
abhay singh
 
20. Object-Oriented Programming Fundamental Principles
Intro C# Book
 
Net Interview-Questions 1 - 16.pdf
PavanNarne1
 
20 Object-oriented programming principles
maznabili
 
29csharp
Sireesh K
 
C# Unit 2 notes
Sudarshan Dhondaley
 
(5) c sharp introduction_object_orientation_part_ii
Nico Ludwig
 
Polymorphism in C# Function overloading in C#
Abid Kohistani
 
Object oriented programming Fundamental Concepts
Bharat Kalia
 
SAD04 - Inheritance
Michael Heron
 
Ad

More from Eng Teong Cheah (20)

PDF
Modern Cross-Platform Apps with .NET MAUI
Eng Teong Cheah
 
PDF
Efficiently Removing Duplicates from a Sorted Array
Eng Teong Cheah
 
PDF
Monitoring Models
Eng Teong Cheah
 
PDF
Responsible Machine Learning
Eng Teong Cheah
 
PDF
Training Optimal Models
Eng Teong Cheah
 
PDF
Deploying Models
Eng Teong Cheah
 
PDF
Machine Learning Workflows
Eng Teong Cheah
 
PDF
Working with Compute
Eng Teong Cheah
 
PDF
Working with Data
Eng Teong Cheah
 
PDF
Experiments & TrainingModels
Eng Teong Cheah
 
PDF
Automated Machine Learning
Eng Teong Cheah
 
PDF
Getting Started with Azure Machine Learning
Eng Teong Cheah
 
PDF
Hacking Containers - Container Storage
Eng Teong Cheah
 
PDF
Hacking Containers - Looking at Cgroups
Eng Teong Cheah
 
PDF
Hacking Containers - Linux Containers
Eng Teong Cheah
 
PDF
Data Security - Storage Security
Eng Teong Cheah
 
PDF
Application Security- App security
Eng Teong Cheah
 
PDF
Application Security - Key Vault
Eng Teong Cheah
 
PDF
Compute Security - Container Security
Eng Teong Cheah
 
PDF
Compute Security - Host Security
Eng Teong Cheah
 
Modern Cross-Platform Apps with .NET MAUI
Eng Teong Cheah
 
Efficiently Removing Duplicates from a Sorted Array
Eng Teong Cheah
 
Monitoring Models
Eng Teong Cheah
 
Responsible Machine Learning
Eng Teong Cheah
 
Training Optimal Models
Eng Teong Cheah
 
Deploying Models
Eng Teong Cheah
 
Machine Learning Workflows
Eng Teong Cheah
 
Working with Compute
Eng Teong Cheah
 
Working with Data
Eng Teong Cheah
 
Experiments & TrainingModels
Eng Teong Cheah
 
Automated Machine Learning
Eng Teong Cheah
 
Getting Started with Azure Machine Learning
Eng Teong Cheah
 
Hacking Containers - Container Storage
Eng Teong Cheah
 
Hacking Containers - Looking at Cgroups
Eng Teong Cheah
 
Hacking Containers - Linux Containers
Eng Teong Cheah
 
Data Security - Storage Security
Eng Teong Cheah
 
Application Security- App security
Eng Teong Cheah
 
Application Security - Key Vault
Eng Teong Cheah
 
Compute Security - Container Security
Eng Teong Cheah
 
Compute Security - Host Security
Eng Teong Cheah
 

Recently uploaded (20)

PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 

Xamarin: Inheritance and Polymorphism

  • 1. Inheritance & Polymorphism Eng Teong Cheah Microsoft MVP Windows Development
  • 3. Inheritance C# is an object oriented programming language so it supports one key feature of OOPS; Inheritance. In general, Inheritance can be explained as acquiring the properties of the parent. For this, we will use the most common example of the car class. You can see Car is an Object who has basic feature like name, height, no of wheels. It has two specialized version one is sedan and other is hatchback. Both sedan and hatch back has all the basic feature of car and some specialized property of their own. This feature is known as inheritance.
  • 4. Inheritance When a child class has all the features of base class plus its own specialized properties. Then this phenomenon is known as inheritance.
  • 5. Inheritance Types of inheritance supported by C# are follows: - Single inheritance Single base class and single derived class. - Multilevel inheritance B derive from A and C derive from B. - Hierarchical inheritance B and C both derived from A. - Multiple inheritance using Interfaces Class D derived from Interface A, Interface B and Class C.
  • 6. Inheritance Preventing a Class from Being Inherited C# We can prevent the class from Being Inherited by Other Class by putting Sealed Keyword in class. See Example Below:- sealed class stringHandler { public string inputString { get; set; } public string OutputString { get; set; } public stringHandler(string inputstring) { this.inputString = inputString; } public String FormatString() { // Some Code here } }
  • 7. Inheritance Constructor initialization C# Inheritance See the car example on top of this page, if we create an object of HatchBack class . The constructor initialization series is given below – HatchBack hb = new HatchBack("hatchback",4,125,40,true); 1. First Car constructor is initialized public Car(string name, int wheelcount, float length, float breadth) { this.Name = name; this.WheelCount = wheelcount; this.length = length; this.breadth = breadth; }
  • 8. Inheritance 2. Second Hatchback Constructor will be initialized public HatchBack(string name, int wheelcount, float length, float breadth, bool isconvertible) : base(name, wheelcount, length, breadth) { this.IsConvertible = isconvertible; } So, from these examples we can say that constructor initialization in inheritance will always follow from base to derived downwards.
  • 9. Inheritance Calling Base class’s Constructor in Inherited C# Classes : Base class constructor is called in derived class using base Keyword. See Car example on top of the page Calling a Base class’s Hidden members in inherited class C# : Base class hidden member function can be called by using base.functionname syntax. See Example below -
  • 10. Inheritance Type Casting in Inheritance C# Parent class reference can hold child class reference but opposite is not true. Casting an object to a parent class is called upcasting. Casting an object to child class is called downcasting. See Example below - We have Draw() method both in base class and derived class. But the see which one is called when. If the Shape class’s Draw() Method is declared as virtual and overridden in Oval class’s Draw() method then result would be different. Result would be. Output when Draw() method will be declared as Virtual and overridden in derived class : Shape Drawn Oval Drawn Oval Drawn
  • 12. Polymorphism Polymorphism is one of the key features of OOPS. Polymorphism can be broken as below. Polymorphism =Poly + morphism =Multiple + forms. Polymorphism is simply calling derived class methods from base class reference during runtime. It is the behavioural change of methods depending upon the instance called at runtime.
  • 13. Polymorphism Before we understand it in polymorphism in C# language, let’s understand it with a simple fantasy example. A mermaid, yes a mermaid. Viola……But how a mermaid is related to Polymorphism see image below. Mermaid shows a polymorphic behavior according to environment. Mermaid behaves like human while on earth and as a fish while in water.
  • 14. Example Class Hierarchy Let's assume the following simple class hierarchy with classes A, B and C for the discussions in this text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the easier examples, we will only refer to a part of this class hierarchy.
  • 15. Inherited Methods A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses
  • 16. Inherited Methods The method Foo() can be overridden in classes B and C:
  • 17. Inherited Methods There are two problems with this code. - The output is not really what we, say from Java, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual. An example using virtual methods and polymorphism will be given in the next section. - Although the code compiles and runs, the compiler produces a warning: ...polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()' This issue will be discussed in section Hiding and Overriding Methods.
  • 18. Virtual and Overridden Methods Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.
  • 19. Method Hiding Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:
  • 20. Combining Method Overriding and Hiding Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
  • 21. Combining Method Overriding and Hiding A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
  • 22. Demo