C# Encapsulation, Inheritance and Polymorphism


C# is one of today's most popular programming languages and supports the object-oriented programming (OOP) paradigm. The basic principles of OOP include encapsulation, inheritance, and polymorphism. In this article, we will examine in detail how these principles are implemented in the C# language.

What is Encapsulation?

Encapsulation is an OOP principle used to protect an object's internal state and restrict external access. Keeping data (properties) and behaviors (methods) together allows objects to be managed securely. In C#, encapsulation is achieved using access modifiers.

C# Encapsulation Example

public class Arac
{
    private string _marka;
    private string _model;

    public string Marka
    {
        get { return _marka; }
        set { _marka = value; }
    }

    public string Model
    {
        get { return _model; }
        set { _model = value; }
    }
}

What is Inheritance?

Inheritance allows a class to inherit properties and methods from another class. In this way, it prevents code repetition and enables more organized and efficient code writing. In the C# language, inheritance is implemented with the ':' operator when defining a class.

C# Inheritance Example

public class Araç
{
    public string Marka { get; set; }
    public string Model { get; set; }
}

public class Otomobil : Araç
{
    public int Kapasite { get; set; }
}

What is Polymorphism?

Polymorphism is the ability of an object to behave in different ways. This concept is implemented by method overloading and method overriding. In the C# language, polymorphism means using the same method name in different ways.

C# Polymorphism Example

public class Hayvan
{
    public virtual void SesVer()
    {
        Console.WriteLine("Hayvan ses verir.");
    }
}

public class Kedi : Hayvan
{
    public override void SesVer()
    {
        Console.WriteLine("Miyav!");
    }
}

As a result, encapsulation, inheritance, and polymorphism are important concepts in the software development process in the C# language. These principles allow developers to write more organized, secure, and reusable code. Seeing how these concepts are implemented using the C# programming language will help you improve your skills as a developer.