Home › C# › C# – Classes
C# · Feb 16, 2015 · 2 MIN READ

C# – Classes

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:

 

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.