Classes
Explore the fundamentals of classes in C#, including how to create and instantiate them, the role of constructors, and how to manage fields and methods. Understand object-oriented principles to build structured and maintainable C# programs using classes effectively.
We'll cover the following...
C# is an object-oriented language, which means that C# programs are a set of interconnected objects.
A class is an object’s definition, and an object is an instance of a class. We can understand this through an analogy. Consider a blueprint for a car. The class is the blueprint, and the actual object is an instance of the Car class. Another example of a class is an abstract concept of a rectangle. Concrete examples that we draw are instances of this class.
Note: In older versions of C#, the default template explicitly included a Program class with a Main() method. In modern .NET, we use top-level statements, which allow us to write executable code directly in Program.cs without the boilerplate class and method wrapper. The compiler handles creating the entry point for us.
Creating classes
A class represents a user-defined type. A class is created using the class keyword:
class Car{}
A class can be defined inside or outside a namespace, or inside another class. Typically, classes are placed in separate files.
Note: Best practice dictates creating a new file for a class and placing it inside a namespace.
The following example demonstrates how to define a class using a file-scoped ...