Difference between Static and Non-Static

As you may have seen, I have been using the keyword static in some cases and not in other cases. Let's understand the difference.

When we write code such as

Car car = new Car("John Doe", "Honda", "Civic", "White");
car.ChangeOwner("Jane Doe");

We are editing the instance of a car object. This is dealing with non static variables.

In our current Car class, we do not have any static variables so lets add one. In order to keep track of all cars that are created, we should create a static variable. A static variable is tied to the class not the instance of a class.

Right below our non static variables, we will add this line of code

public static int NumberOfCars {get; private set;}

Now, in the constructors, where the objects are created, we have to add a line of code that increments the variable, NumberOfCars.

At the end of each constructor, add this line

NumberOfCars++;

We can test this out by making two objects in our Program.cs and print out the NumberOfCars.

Car car = new Car("Rohit", "Honda", "Civic", "white");
Car car2 = new Car("Rohan", "Honda", "Civic", "white");
Console.WriteLine(Car.NumberOfCars);

Because static variables are tied to the class, to use NumberOfCars, we have to use the class name: Car. NOT an instance of a car.

The output of this code is going to be 2. We have made 2 car instances and each time we did, the NumberOfCars variables got incremented. It is very important to understand the use of static and non static variables because classes are the foundation of any C# program.

Bank Account Project

At this moment, there is no need for any type of static variables in the Bank Account simulation. However, in the past sections, we did remove any static methods and variables we may have had because we converted to using classes and objects.

Next Section: Mini Project 2