Notifications
Clear all
Topic starter 01/08/2025 11:52 pm
In C#, classes are the blueprint for creating objects. They define the structure and behavior of an object by encapsulating data (fields/properties) and functionality (methods). Let’s explore the magic behind classes:
🏗️ Basic Class Definition
public class Dog
{
// Fields or Properties
public string Name { get; set; }
public string Breed { get; set; }
// Constructor
public Dog(string name, string breed)
{
Name = name;
Breed = breed;
}
// Method
public void Speak()
{
Console.WriteLine($"{Name} says woof!");
}
}
🐾 Creating an Object
Use the new
keyword:
Dog myDog = new Dog("Fido", "Labrador");
myDog.Speak(); // Output: Fido says woof!
🔐 Access Modifiers
Control visibility:
Modifier | Description |
---|---|
public |
Accessible from anywhere |
private |
Accessible only within the class |
protected |
Accessible in the class and subclasses |
internal |
Accessible within the same assembly |
🧬 Inheritance
Build a child class from a parent:
public class Puppy : Dog
{
public Puppy(string name, string breed) : base(name, breed) {}
public void Play()
{
Console.WriteLine($"{Name} is playing!");
}
}
📦 Other Features
- Static members: Belong to the class, not the instance
- Abstract classes: Cannot be instantiated; meant to be extended
- Interfaces: Define a contract for what a class must implement
- Encapsulation: Hide internal details, expose necessary functionality