C# Classes
Blueprints for creating objects.
C# Classes
C# is an object-oriented programming language.
Everything in C# is associated with classes and objects, along with 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 drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the class keyword:
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 an object of Car, specify the class name, followed by the object name, and use the keyword new:
Car myObj = new Car();
Console.WriteLine(myObj.color);
Examples
Create a Class and Object
Basic class and object creation.
using System;
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}Multiple Objects
Creating two objects from one class.
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);
}
}Class Attributes
Setting attribute values.
using System;
class Car
{
string model;
string color;
int year;
static void Main(string[] args)
{
Car Ford = new Car();
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
Car Opel = new Car();
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}