This guide covers the basics of creating classes and objects in C#, essential concepts in object-oriented programming (OOP). You’ll learn how to define a class, create objects, and work with their properties and methods.
What is a Class?
A class in C# acts as a template that defines the structure and behavior of objects. Key components of a class include:
- Properties – Attributes that store data (e.g., a person’s name or age).
- Methods – Functions that define actions an object can perform.
- Constructors – Special methods that initialize objects when they’re created.
For example, a Person class might include properties like Name and Age, a constructor to set these values, and a method to display the person’s details.
Defining a Class in C#
To define a class, use the following syntax:
- Access Modifier – Determines visibility (e.g., public).
- class Keyword – Declares a class.
- Class Name – An identifier (e.g., Person).
Example: A Simple Person Class
public class Person
{
// Properties
public string Name { get; set; }
public int Age { get; set; }
// Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
// Method
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
Breaking Down the Example
- public → The class is accessible from anywhere.
- Person → The class name.
- Name and Age → Properties storing data.
- Person(string name, int age) → Constructor initializing the object.
- DisplayInfo() → A method that prints the object’s details.
Creating Objects (Instantiation)
An object is an instance of a class, created using the new keyword:
Person neighbor = new Person("John Doe", 30);
What’s Happening Here?
- Person → The class type.
- neighbor → The object’s name.
- new Person(“John Doe”, 30) → Calls the constructor to create the object.
Accessing Object Members with Dot Notation
Once an object is created, you can interact with its properties and methods using a dot (.):
Examples
- Modifying a Property:
neighbor.Age = 31; <em>// Updates the Age</em>
- Calling a Method:
neighbor.DisplayInfo(); <em>// Output: "Name: John Doe, Age: 31"</em>
Conclusion
Classes and objects are the foundation of OOP in C#, enabling modular, reusable, and maintainable code. By mastering these concepts, you’ll be better equipped to build structured and scalable applications.