C# Classes and Objects

You learned in the preceding chapter that C# is the language of object-oriented programming language.

Everything in C # is associated with classes and objects, as well as its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as driving and brakes.

A class is like an object constructor, or a "blueprint" for creating things


Create a Class

To create a class, use the class keyword:

Create a class named "Car" with a variable color:

class Car 
            {
              string color = "red";
            }

Create 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 a Car object, specify a class name, followed by an object name, and use a new keyword:

Example

Create an object called "myObj" and use it to print the value of color:

class Car 
            {
              string color = "red";
            
              static void Main(string[] args)
              {
                Car myObj = new Car();
                Console.WriteLine(myObj.color);
              }
            }

Multiple Objects

You can create multiple objects in one category:

Example

Create two objects of Car:

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);
              }
            }

Using Multiple Classes

You can also create a class item and access it in another class. This is often used for better class planning (one class has all the fields and routes, while the other class has a Main() method (code to use)).

  • prog2.cs
  • prog.cs

prog2.cs

class Car 
            {
              public string color = "red";
            }
            

prog.cs

class Program
            {
              static void Main(string[] args)
              {
                Car myObj = new Car();
                Console.WriteLine(myObj.color);
              }
            }