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.
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