C# Classes and Objects
A class is the blueprint for an object, and an object is a working instance built from that blueprint. In this lesson you will learn how to define a class, create objects from it with the new keyword, and give each object its own data.
Creating a Class
You define a class with the class keyword followed by a name. By convention, class names in C# start with an uppercase letter. Inside the curly braces you place the class members, such as fields (variables that hold data) and methods (functions that describe behavior).
Defining a class
class Car
{
// A field to store data
public string color = "blue";
}Creating an Object
A class on its own does nothing until you create an object from it. You create an object with the new keyword. The object is stored in a variable whose type is the class name. Once you have an object, you access its members using the dot (.) operator.
Creating and using an object
class Car
{
public string color = "blue";
}
class Program
{
static void Main()
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
// Output:
// blueMultiple Objects
You can create as many objects from one class as you need. Each object holds its own copy of the data, so changing one object's fields does not affect the others. This is what makes classes reusable.
Two independent objects
class Car
{
public string color = "blue";
}
class Program
{
static void Main()
{
Car car1 = new Car();
Car car2 = new Car();
car2.color = "red";
Console.WriteLine(car1.color);
Console.WriteLine(car2.color);
}
}
// Output:
// blue
// red- Use the class keyword to define a class.
- Class names start with an uppercase letter by convention.
- Use the new keyword to create an object from a class.
- Access members of an object with the dot (.) operator.
Exercise: C# Classes and Objects
Which keyword creates a new instance of a class in C#?