Home › C# › C# – Inheritance
C# · Feb 17, 2015 · 1 MIN READ

C# – Inheritance

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 { get; set; }
 
    }
}

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 { get; set; }
        public string model { get; set; }
        public int year { get; set; }
 
        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.

Carl de Souza
Keep learning. Keep building.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.

Subscribe on YouTube →
Carl de Souza Enterprise Architect at Microsoft · AI Technology Expert

Leave a Reply

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

Carl de Souza
KEEP LEARNING. KEEP BUILDING.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.