C# – Inheritance

Leave a comment

Carrying on from our previous transport post, we currently have a car class that has some properties. However, a car is a type of vehicle. What if we wanted to expand to other types of vehicles in our solution? Let’s add a vehicle class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Transportation
{
    class Vehicle
    {
    }
}

Now, as we shoudn’t create an object out of “vehicle”, we will define this as an abstract class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Transportation
{
    public abstract class Vehicle
    {
        public int wheels { getset; }
 
    }
}

If we try to create an instance of Vehicle, we get the error message below:

Now, we can set the base property in the constructor of the class, in this case, set wheels to 4:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Transportation
{
    public class Car : Vehicle
    {
        public string make { getset; }
        public string model { getset; }
        public int year { getset; }
 
        public Car()
        {
            base.wheels = 4;
        }
    }
}

This produces the output of 4 when queried:

We can move more properties into the base class if it makes sense, and we can use that to define other vehicle types.

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

See more articles on: C#

Leave a Reply

Your email address will not be published. Required fields are marked *