Classes are the building blocks of object-oriented programming in C#. They are used to create objects, which are instances of classes. This tutorial covers the basics of classes, their properties, methods, constructors, inheritance, and best practices.
A class in C# is defined using the class keyword, followed by the class name and a pair of curly braces containing the class members.
Example:
namespace ClassExamples;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Properties are members of a class that provide a flexible mechanism to read, write, or compute the values of private fields. Properties are defined using the get
and set
accessors.
namespace ClassExamples;
class Person
{
private string name;
private int age;
public string Name
{
get => name;
set => name = value;
}
public int Age
{
get => age;
set => age = value;
}
}
Methods are members of a class that define the actions the class can perform. Methods are defined using a return type, a name, and a pair of parentheses that may contain parameters.
Example:
namespace ClassExamples;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
Constructors are special methods that are called when an instance of a class is created. They have the same name as the class and do not have a return type.
Example:
namespace ClassExamples;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
// Default constructor
public Person()
{
Name = "Unknown";
Age = 0;
}
// Parameterized constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit members from another class. The class that inherits is called the derived class, and the class being inherited from is called the base class.
Example:
namespace ClassExamples;
// Base class
class Animal
{
public string Name { get; set; }
public void Eat()
{
Console.WriteLine($"{Name} is eating.");
}
}
// Derived class
class Dog : Animal
{
public string Breed { get; set; }
public void Bark()
{
Console.WriteLine($"{Name} is barking.");
}
}
Access modifiers control the accessibility of class members. The most common access modifiers are public, private, protected, and internal.
Example:
namespace ClassExamples;
class Person
{
// Public property
public string Name { get; set; }
// Private field
private int age;
// Public method
public void SetAge(int age)
{
if (age > 0)
{
this.age = age;
}
}
// Protected method
protected void DisplayAge()
{
Console.WriteLine($"Age: {age}");
}
}
Understanding and using classes effectively is crucial for writing clean and maintainable C# code. This tutorial covered the basics of classes, properties, methods, constructors, inheritance, access modifiers, and best practices for creating and using classes in C#.