C# / Object-Oriented Programming in C#

Implementing Encapsulation and Abstraction

In this tutorial, we will explore encapsulation and abstraction in C#. You will learn how to hide data within classes, define abstract classes and methods, and understand their be…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers object-oriented programming concepts such as classes, objects, inheritance, and polymorphism.

1. Introduction

Goal of the Tutorial

The aim of this tutorial is to explain the concepts of Encapsulation and Abstraction in C# and how to implement them effectively.

Learning Outcome

  • Understanding of what Encapsulation and Abstraction are.
  • How to hide data within classes using encapsulation.
  • How to define abstract classes and methods using abstraction.

Prerequisites

Basic knowledge of C# programming language.

2. Step-by-Step Guide

Encapsulation

Encapsulation is a concept of binding or encapsulating the data and the methods that manipulate the data into a single unit. In other words, it is a protective shield that prevents the data from being accessed by the code outside this shield.

Example:

public class Employee
{
    // private data member
    private string name;

    // public method to access and mutate private data member
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

In this example, name is a private data member encapsulated inside the Employee class. It can be accessed and mutated only through the public property Name.

Abstraction

Abstraction is a process of hiding the implementation details and showing only the functionality to the user. It lets you focus on what the object does instead of how it does it.

Example:

public abstract class Shape
{
    public abstract double Area();
}

public class Rectangle : Shape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public override double Area()
    {
        return Width * Height;
    }
}

In this example, Shape is an abstract class and Area is an abstract method. The Rectangle class inherits Shape class and implements the Area method.

3. Code Examples

Encapsulation Example:

public class Student
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
}

// Usage
Student student = new Student();
student.Name = "John Doe"; // set operation
Console.WriteLine(student.Name); // get operation, print: John Doe

Here, _name is a private data member enclosed within the Student class. We access it using the public property Name.

Abstraction Example:

public abstract class Animal
{
    public abstract void Sound();
}

public class Dog : Animal
{
    public override void Sound()
    {
        Console.WriteLine("Dog barks");
    }
}

// Usage
Animal myDog = new Dog();
myDog.Sound(); // print: Dog barks

Here, Sound is an abstract method of the abstract class Animal. The Dog class inherits Animal and implements the Sound method.

4. Summary

We've covered encapsulation and abstraction in C#. Encapsulation is about hiding and safeguarding data. Abstraction, on the other hand, is about hiding the implementation and exposing the functionality.

Next Steps

To further improve your skills, practice these concepts by creating more complex classes and methods.

Additional Resources

5. Practice Exercises

  1. Create a Person class with encapsulation for Name and Age properties.
  2. Create an abstract Vehicle class with an abstract method Move and implement it in the Car and Bicycle classes.

Solutions:

  1. Encapsulation Exercise:
public class Person
{
    private string _name;
    private int _age;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
}
  1. Abstraction Exercise:
public abstract class Vehicle
{
    public abstract void Move();
}

public class Car : Vehicle
{
    public override void Move()
    {
        Console.WriteLine("Car is driving");
    }
}

public class Bicycle : Vehicle
{
    public override void Move()
    {
        Console.WriteLine("Bicycle is pedaling");
    }
}

With these exercises, you should be able to grasp the concept of encapsulation and abstraction. Practice more to get familiar with these concepts.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Color Palette Generator

Generate color palettes from images.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help