In this example and series of examples, I will go through some object oriented and C# concepts. We will use an example of building a transport system, using Cars as an example.
First, create a C# project for a class library called “Transportation”. Also, let’s create a new console application called Carl.TestTransportation. We will use that to test our class working.
Let’s star with characteristics of a car. Cars have:
- Make. E.g. Ferrari
- Model, E.g. Testarossa
- Year, E.g. 1984
These characteristics will be our class properties. We can add these properties to our class:
And in our test program, create an instance of the class. We will add a ReadLine so we can run the console application and see the output.
At the moment, our instance does nothing and has no properties displayed. This is because we did not specify the properties to be public.
If we change the properties to be public, we will see these in our class:
We now see the attributes appearing:
To test our class, we can create an instance of it in our test solution. Firstly, we will need to add a reference to the class:
Next, let’s add some code to create an instance of our new class and assign a value to the public fields:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Transportation; namespace Carl.TestTransportation { class Program { static void Main(string[] args) { Transportation.Car ferraritest = new Transportation.Car(); ferraritest.make = "ferrari"; Console.WriteLine(ferraritest.make); Console.ReadLine(); } } }
We can see the output displayed:
Now, in our example we set the fields to be public. However, we can also use automatic properties to set the values, which will come in useful later.
To do this, add { get; set; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Transportation { public class Car { public string make { get; set; } public string model { get; set; } public int year { get; set; } } }
Note the code runs the same with this change:
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