Classes and Objects in C#
Classes and Objects in C#
Let's dive into a foundational concept in Object-Oriented Programming (OOP): Classes and Objects. Whether you have explored OOP concepts in other programming languages or are encountering them for the first time, this overview will serve you well.
Object-Oriented Programming (OOP) is a programming paradigm centered around objects rather than actions and data rather than logic. It allows for organizing software design around data, or objects, rather than functions and logic.
Classes and objects are the building blocks of OOP:
- A
classacts as a blueprint for creating objects. - Objects are instances of a
class.
Understanding these basics is essential before moving on to more advanced OOP topics like inheritance, polymorphism, and encapsulation.
Declaring and Defining Classes
In C#, a class is defined using the class keyword. Here's a simple example:
In this snippet, we define a Person class with fields name and age, and member functions, including a constructor and a copy constructor. We also have a Display function to print the object's data.
Creating Objects from Classes
Once you have defined a class, you can create objects (instances of the class). Here’s how we can create and use objects of the Person class:
Here, we create an object, person, with the name "Alice" and age 30, and another object, personCopy, which is a copy of the first object using the copy constructor. Both objects display their data using the Display method.
