DEV Community

Shivanshu Sharma
Shivanshu Sharma

Posted on

Wrapper classes in C#

Let’s dive into the concept of wrapper classes in C#.

A wrapper class is any class that “wraps” or “encapsulates” the functionality of another class or component. These wrapper classes are useful because they provide a level of abstraction from the implementation details of the underlying class or component1. In other words, they allow you to interact with the wrapped class in a more convenient and controlled manner.

Here’s a simple example to illustrate the concept of a wrapper class:

Suppose we have two classes: TaxCalculator and SalaryCalculator. The TaxCalculator class contains methods to calculate taxes, while the SalaryCalculator class is responsible for calculating salaries. We want to use the tax calculation functionality from TaxCalculator within the SalaryCalculator class without exposing the details of how taxes are calculated.

Let’s create a wrapper class called Wrapper that encapsulates the TaxCalculator functionality:

C#

**_using System;

namespace WrapperExample
{
class TaxCalculator
{
public int CalculateTax(int salary)
{
// Implementation details for tax calculation
// ...
return taxAmount;
}
}

class Wrapper
{
    private TaxCalculator taxCalculator = new TaxCalculator();

    public int CalculateSalaryWithTax(int salary)
    {
        // Wrapping the tax calculation functionality
        int taxAmount = taxCalculator.CalculateTax(salary);
        return salary - taxAmount;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Wrapper salaryWrapper = new Wrapper();
        int salary = 1000;
        int netSalary = salaryWrapper.CalculateSalaryWithTax(salary);_**

        Console.WriteLine($"Net salary after tax: {netSalary}");
        Console.ReadLine();
    }
}
Enter fullscreen mode Exit fullscreen mode

}
In this example:

The Wrapper class encapsulates the TaxCalculator functionality by creating an instance of TaxCalculator internally.
The CalculateSalaryWithTax method in the Wrapper class calculates the net salary after deducting taxes.
By using the Wrapper class, we achieve two important goals:

We hide the details of tax calculation from the SalaryCalculator class.
We provide a cleaner and more abstract interface for calculating salaries.
Remember that wrapper classes can be used in various scenarios, not just for tax calculations. Whenever you need to encapsulate functionality from another class or component, consider using a wrapper class to improve code organization and maintainability.

I hope this helps you understand the concept of wrapper classes in C#! If you have any further questions, feel free to ask. 😊👍

Top comments (0)