C# Tutorial For Beginners: Classes and Objects
Updated: Jan 19, 2022
C# is an object-oriented programming language. As such, it contains classes, object attributes, and more. When you define a class, it's similar to creating a blueprint for creating class objects. Each defined object (instance of the class) consists of what properties, attributes, and methods are defined in the class.
Defining a class
To create a new class, we will use the ‘class’ keyword followed by the class name:
class Vehicle
{
public string vehiclecolor;//Class variable
public int VehicleNumber { get; set; }//Class Propertie
}
Create an Object
An object is created from a specific class. Now that we have the class ready, we can use this to create an object of the Vehicle class:
class Vehicle
{
public string vehiclecolor = "Black";//Class variable
}
class Human
{
public string name;
public int age;
}
class Program
{
static void Main(string[] args)
{
//Create an Object of the Vehicle class
Vehicle vehicle_1 = new Vehicle();
//Print Vehicle color
Console.WriteLine(vehicle_1.vehiclecolor);
//Create another object of the Vehicle class
Vehicle vehicle_2 = new Vehicle();
//Print Vehicle color
Console.WriteLine(vehicle_1.vehiclecolor);
//Create an Object of the Human class and defining its variables
Human Human_1 = new Human() {age =13 , name = "david"};
}
}