C# is an object-oriented programming language. Nearly everything in C# is an object and every object is an instance of a class. Many classes are built into C# and other languages by default. Examples include List
and Dictionary
. However, the real power of programming comes from creating custom objects from our own custom classes.
A class is like a blueprint that defines the behavior and attributes of the objects that live inside that class. While each individual object in a class may have different attributes, they all have access to the same methods from the class. We have some experience working with classes from Intro. The general concept is fairly similar in C#, but with different syntax and conventions.
Let's walk through creating a custom C# class. We'll build a used car dealership for Lonny's Lemons, which specializes in selling some of the most ridiculed cars ever made. Our website must display details for each car on our lot. To do this, we'll make a Car
class to instantiate Car
objects.
We can think of the Car
class as reflecting any generic car on Lonny's lot. Meanwhile, a specific instance of the Car
class might be a blue Pontiac Aztek with 600,000 miles on it.
We'll create a new Car.cs
file and insert the following:
using System;
using System.Collections.Generic;
public class Car
{
public string MakeModel;
public int Price;
public int Miles;
}
When we use the keyword class
, we are declaring the class. We use the class
keyword followed by the name of the class. The name must use UpperCamelCase capitalization and contain no spaces or underscores. A set of curly braces should start directly on the next line as seen above. The contents of the class resides between these curly braces.
We now have a Car
class with three variables:
MakeModel
: a string
containing the make and model of the vehicle.Price
: an int
for the vehicle's cost.Miles
: an int
for the number of miles a Car
has on it.The variables above are known as fields in C#. A field is a variable of any type that is declared within a class. Fields should always be written in PascalCase. Note that fields are not the same as properties. In C#, a property exposes a field. Since our fields are currently public and available everywhere, they are fully exposed, so they are operating much like properties. If this distinction isn't clear yet, don't worry. We'll cover this further in a future lesson.
Each field in our class is preceded by the word public
. This is an access modifier. An access modifier determines how this information can be accessed. Declaring these fields as public
means they're available to any other part of the application. Other potential options include private
and protected
. We'll cover access level modifiers in more detail later. For now, we'll simply make everything public
.
We want users to see Car
objects in the console so we'll add basic boilerplate code for a console application.
using System;
using System.Collections.Generic;
public class Car
{
public string MakeModel;
public int Price;
public int Miles;
}
public class Program
{
public static void Main()
{
}
}
We've added our Program
class. Since both Car
and Main
live in the same file, our user interface code in Main()
will automatically have access to our Car
class due to its scope. In future lessons, we'll separate these classes into different files, but for now, we'll keep things simple.
Within our Main()
method, we'll create four Car
objects to work with, adding them all to a List
named Cars
:
using System;
using System.Collections.Generic;
public class Car
{
public string MakeModel;
public int Price;
public int Miles;
}
public class Program
{
public static void Main()
{
Car volkswagen = new Car();
volkswagen.MakeModel = "1974 Volkswagen Thing";
volkswagen.Price = 1100;
volkswagen.Miles = 368792;
Car yugo = new Car();
yugo.MakeModel = "1980 Yugo Koral";
yugo.Price = 700;
yugo.Miles = 56000;
Car ford = new Car();
ford.MakeModel = "1988 Ford Country Squire";
ford.Price = 1400;
ford.Miles = 239001;
Car amc = new Car();
amc.MakeModel = "1976 AMC Pacer";
amc.Price = 400;
amc.Miles = 198000;
}
}
We create four new instances of the Car
class. Creating an object like this is called instantiation because the new object is an instance of its class. Each object created above (including yugo
, ford
, and amc
) is an instance of the class Car
.
Like all C# variables, we also declare a type. Each new object above has a Car
type because they're instances of our Car
class.
We use the keyword new
because each of these Car
s is a new instance.
We end the line with Car()
. We’ll address what the parentheses are for in an upcoming lesson. For now, just know they're required.
To store a value in an object, we use this operator: .
. This is called the object operator. When we state yugo.MakeModel = "1980 Yugo Koral";
, we're looking for the makeModel
value of the object stored in the variable yugo
. Then we use the assignment operator =
to set the value of that field.
Now let's display these cars in the console. We'll create a Cars
List
and add a foreach
loop to Main()
below our instantiated Car
s:
...
public class Program
{
public static void Main()
{
//Code for instantiating four cars is here.
List<Car> Cars = new List<Car>() { volkswagen, yugo, ford, amc };
foreach(Car automobile in Cars)
{
Console.WriteLine(automobile.MakeModel);
}
}
}
...
We create a List
of type Car
called Cars
. Here we instantiate a new list of cars with each of our instances of Car
inside it. Our loop iterates through our list of cars and returns the MakeModel
of each.
Once we add our Car.csproj
file, we can compile and launch the application with the command dotnet run
. A list of all cars appear in the console. We've successfully created another class-based C# program. In the next lesson, we'll walk through adding class methods to our new Car
class.
Access Modifier: determines how information can be accessed. private
, public
and protected
are most common.
Class: A blueprint that defines the behavior and attributes of a group of objects. We use the class
keyword to declare a class: class Car
.
Field: A variable of any type declared in a class. These are written in PascalCase. They are usually private.
Instance: An object created within a class. We use the new
keyword to create an instance.
Instantiation: To create a new instance of a class.
Object Operator: We use this to store a value in an object. For example: yugo.MakeModel
. We then use the assignment operator to assign the value: yugo.MakeModel = "1980 Yugo Koral";
.
Property: Exposes a field so it can be used throughout an application. They are public.
Public: Available throughout an application.
Private: Available only within a class.
Lesson 1 of 10
Last updated more than 3 months ago.