C# Classes and Objects

C# Classes and Objects

In the previous lesson, we learned that C# is an object-oriented programming language. Everything in C# revolves around Classes and Objects.

A Class is like an object constructor, or a "blueprint" for creating objects. An Object is a specific instance of a class.


Creating a Class

To create a class, use the class keyword. By convention, class names should start with an uppercase letter.

Let's create a class named Car with a single field (a variable inside a class):

class Car 
{
  // A field inside the class
  string color = "red"; 
}

Creating an Object

An object is created from a class. We have already created the class named Car, so now we can use this to create objects.

To create an object of Car, specify the class name, followed by the object name, and use the new keyword.

Example: Creating an Object

using System;

class Car { string color = "red";

static void Main(string[] args) { // Creating an object named 'myObj' Car myObj = new Car(); Console.WriteLine(myObj.color); } }

When you run this code, the output will be: red.


Multiple Objects

You can create multiple objects of one class. Each object functions independently of the others.

Example: Multiple Objects

using System;

class Car { string color = "red";

static void Main(string[] args) { Car myObj1 = new Car(); Car myObj2 = new Car(); Console.WriteLine(myObj1.color); Console.WriteLine(myObj2.color); } }

Note: While it is possible to declare a class and a `Main` method in the same file, it is a common practice in larger projects to organize classes into multiple files for better maintainability.


Exercise

?

Which keyword is used to create an object from a class in C#?