.NET HELP

C# Object Oriented (How It Works For Developers)

Chipego
Chipego Kalinda
April 3, 2024
Share:

Object-oriented programming (OOP) is a fundamental concept in software development, enabling programmers to create modular, reusable, and adaptable code. C#, a modern object-oriented programming language, offers a robust framework for building complex applications. This guide introduces OOP concepts using C#, focusing on practical implementations and coding examples to help beginners understand and apply these principles effectively. We'll also discuss how one could apply these principles with the IronPDF library for C#.

Understanding Object-Oriented Programming Concepts

At the heart of OOP lie several key concepts: classes, objects, inheritance, polymorphism, abstraction, and encapsulation. These concepts allow developers to model real-world entities, manage complexity, and improve the maintainability of their code.

Classes and Objects: The Building Blocks

A class creates individual objects. The class is a blueprint that defines the data and behavior that the objects of the class all share. An object is a manifestation of a class. It embodies real values rather than abstract placeholders defined in the class blueprint.

public class Car // A class declared as 'Car' defines its structure and behavior.
{
    public string Name;
    public string Color;
    public void DisplayInfo()
    {
        Console.WriteLine($"Name: {Name}, Color: {Color}");
    }
}
class Program // This is the program class, serving as the entry point of a C# program.
{
    static void Main(string [] args)
    {
        Car myCar = new Car();
        myCar.Name = "Toyota";
        myCar.Color = "Red";
        myCar.DisplayInfo();
    }
}
public class Car // A class declared as 'Car' defines its structure and behavior.
{
    public string Name;
    public string Color;
    public void DisplayInfo()
    {
        Console.WriteLine($"Name: {Name}, Color: {Color}");
    }
}
class Program // This is the program class, serving as the entry point of a C# program.
{
    static void Main(string [] args)
    {
        Car myCar = new Car();
        myCar.Name = "Toyota";
        myCar.Color = "Red";
        myCar.DisplayInfo();
    }
}

In this example, the Car class has two data members (Name and Color) and one method (DisplayInfo). The Main method, which serves as the entry point of the application, creates an instance of the Car class and assigns values to its fields before calling its method to display these values.

C# Object Oriented (How It Works For Developers): Figure 1 - The console displays the member values(name,color) of the Car Object through the DisplayInfo method

Inheritance: Extending Existing Classes

Inheritance allows a class to inherit the properties and methods of an existing class. The class whose properties are inherited is called the base class, and the class that inherits those properties is called the derived class.

public class Vehicle
{
    public string LicensePlate;
    public void Honk()
    {
        Console.WriteLine("Honking");
    }
}
public class Truck : Vehicle // Truck is a child class derived from the Vehicle base class.
{
    public int CargoCapacity;
}
class Program
{
    static void Main(string [] args)
    {
        Truck myTruck = new Truck();
        myTruck.LicensePlate = "ABC123";
        myTruck.CargoCapacity = 5000;
        myTruck.Honk();
    }
}
public class Vehicle
{
    public string LicensePlate;
    public void Honk()
    {
        Console.WriteLine("Honking");
    }
}
public class Truck : Vehicle // Truck is a child class derived from the Vehicle base class.
{
    public int CargoCapacity;
}
class Program
{
    static void Main(string [] args)
    {
        Truck myTruck = new Truck();
        myTruck.LicensePlate = "ABC123";
        myTruck.CargoCapacity = 5000;
        myTruck.Honk();
    }
}

In this example, Truck is a derived class that extends the Vehicle base class, inheriting its LicensePlate field and Honk method while adding a new field, CargoCapacity.

Polymorphism and Abstraction: Interfaces and Abstract Classes

Polymorphism enables objects to be handled as instances of their base class rather than their specific class. Abstraction allows you to define abstract classes and interfaces that cannot be instantiated but can be used as base classes.

Abstract Classes and Methods

Abstract classes cannot be instantiated and are typically used to provide a common definition of a base class that multiple derived classes can share.

public abstract class Shape
{
    public abstract void Draw();
}
public class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a circle");
    }
}
public abstract class Shape
{
    public abstract void Draw();
}
public class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a circle");
    }
}

Implementing Multiple Interfaces

An interface establishes an agreement, or contract, that classes can fulfill by implementing its defined methods. Classes can implement multiple interfaces, enabling a form of polymorphism.

public interface IDrawable
{
    void Draw();
}
public interface IColorable
{
    void Color();
}
public class CustomShape : IDrawable, IColorable // Defining a new class CustomShape that implements IDrawable and IColorable.
{
    public void Draw()
    {
        Console.WriteLine("Custom shape drawn");
    }
    public void Color()
    {
        Console.WriteLine("Custom shape colored");
    }
}
public interface IDrawable
{
    void Draw();
}
public interface IColorable
{
    void Color();
}
public class CustomShape : IDrawable, IColorable // Defining a new class CustomShape that implements IDrawable and IColorable.
{
    public void Draw()
    {
        Console.WriteLine("Custom shape drawn");
    }
    public void Color()
    {
        Console.WriteLine("Custom shape colored");
    }
}

Encapsulation: Safeguarding Data

Encapsulation is the mechanism of restricting access to certain components of an object and preventing external parties from seeing the internal representation. This is accomplished through the usage of access modifiers.

public class Person
{
    private string name; // Private variable, inaccessible outside the class
    public string Name   // Public property to access the private variable
    {
        get { return name; }
        set { name = value; }
    }
}
// Example showing a simple customer class with encapsulated data
public class Customer
{
    public string Name { get; set; }
    public string Address { get; set; } 
}
public class Person
{
    private string name; // Private variable, inaccessible outside the class
    public string Name   // Public property to access the private variable
    {
        get { return name; }
        set { name = value; }
    }
}
// Example showing a simple customer class with encapsulated data
public class Customer
{
    public string Name { get; set; }
    public string Address { get; set; } 
}

In this example, the name field is private, making it inaccessible outside the Person class. Access to this field is provided through the public Name property, which includes get and set methods.

Practical Use Cases and Coding Examples

Now, we'll explore an example involving multiple classes to demonstrate these principles in action.

using System;
namespace OOPExample
{
    public class Program
    {
        static void Main(string [] args)
        {
            ElectricCar myElectricCar = new ElectricCar();
            myElectricCar.Make = "Tesla";
            myElectricCar.Model = "Model 3";
            myElectricCar.BatteryLevel = 100;
            myElectricCar.Drive();
            myElectricCar.Charge();
        }
    }
    public abstract class Vehicle
    {
        public string Make { get; set; }
        public string Model { get; set; }
        public abstract void Drive();
    }
    public class Car : Vehicle
    {
        public override void Drive()
        {
            Console.WriteLine($"The {Make} {Model} is driving.");
        }
    }
    public class ElectricCar : Car
    {
        public int BatteryLevel { get; set; }
        public void Charge()
        {
            Console.WriteLine("Charging the car.");
        }
        public override void Drive()
        {
            Console.WriteLine($"The {Make} {Model} is driving silently.");
        }
    }
}
using System;
namespace OOPExample
{
    public class Program
    {
        static void Main(string [] args)
        {
            ElectricCar myElectricCar = new ElectricCar();
            myElectricCar.Make = "Tesla";
            myElectricCar.Model = "Model 3";
            myElectricCar.BatteryLevel = 100;
            myElectricCar.Drive();
            myElectricCar.Charge();
        }
    }
    public abstract class Vehicle
    {
        public string Make { get; set; }
        public string Model { get; set; }
        public abstract void Drive();
    }
    public class Car : Vehicle
    {
        public override void Drive()
        {
            Console.WriteLine($"The {Make} {Model} is driving.");
        }
    }
    public class ElectricCar : Car
    {
        public int BatteryLevel { get; set; }
        public void Charge()
        {
            Console.WriteLine("Charging the car.");
        }
        public override void Drive()
        {
            Console.WriteLine($"The {Make} {Model} is driving silently.");
        }
    }
}

In this example, Drive() is an abstract method from the Vehicle abstract class. Car is a derived class that implements Drive(), and ElectricCar is another level down the hierarchy, adding new features like BatteryLevel and its own Drive() implementation. This structure demonstrates abstraction, encapsulation, inheritance, and polymorphism working together in a C# application.

C# Object Oriented (How It Works For Developers): Figure 2 - Console output from the code, printing the output from the drive abstract method and charge method

IronPDF: C# PDF Library

The IronPDF library for .NET is a versatile tool for C# developers, designed to simplify the process of creating, editing, and extracting PDF documents within .NET applications. IronPDF has the ability to easily generate PDFs from HTML strings, URLs, or ASPX files, offering a high level of control over the PDF creation and manipulation process. Additionally, IronPDF supports advanced features like adding headers and footers, watermarking, and encryption, making it a comprehensive solution for handling PDFs in .NET applications.

Example of IronPDF with OOP

Here's a simplified example demonstrating the use of IronPDF within a C# application, incorporating the virtual keyword to illustrate how one might extend IronPDF functionality through inheritance, a core concept in OOP. Suppose we have a base class that generates a basic PDF report and a derived class that extends this functionality to include a custom header:

using IronPdf;
public class BasicReportGenerator
{
    public virtual PdfDocument GenerateReport(string htmlContent)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        return pdf;
    }
}
public class CustomReportGenerator : BasicReportGenerator
{
    public override PdfDocument GenerateReport(string htmlContent)
    {
        var pdf = base.GenerateReport(htmlContent);
        AddCustomHeader(pdf, "Custom Report Header");
        return pdf;
    }
    private void AddCustomHeader(PdfDocument document, string headerContent)
    {
        // Create text header
        TextHeaderFooter textHeader = new TextHeaderFooter
        {
            CenterText = headerContent,
        };
        document.AddTextHeaders(textHeader);
    }
}
class Program
{
    static void Main(string [] args)
    {
        License.LicenseKey = "License-Key";
        // HTML content for the report
        string htmlContent = "<html><body><h1>Sample Report</h1><p>This is a sample report content.</p></body></html>";
        // Using BasicReportGenerator
        BasicReportGenerator basicReportGenerator = new BasicReportGenerator();
        var basicPdf = basicReportGenerator.GenerateReport(htmlContent);
        basicPdf.SaveAs("basic_report.pdf");
        // Using CustomReportGenerator
        CustomReportGenerator customReportGenerator = new CustomReportGenerator();
        var customPdf = customReportGenerator.GenerateReport(htmlContent);
        customPdf.SaveAs("custom_report.pdf");
        Console.WriteLine("PDF reports generated successfully.");
    }
}
using IronPdf;
public class BasicReportGenerator
{
    public virtual PdfDocument GenerateReport(string htmlContent)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        return pdf;
    }
}
public class CustomReportGenerator : BasicReportGenerator
{
    public override PdfDocument GenerateReport(string htmlContent)
    {
        var pdf = base.GenerateReport(htmlContent);
        AddCustomHeader(pdf, "Custom Report Header");
        return pdf;
    }
    private void AddCustomHeader(PdfDocument document, string headerContent)
    {
        // Create text header
        TextHeaderFooter textHeader = new TextHeaderFooter
        {
            CenterText = headerContent,
        };
        document.AddTextHeaders(textHeader);
    }
}
class Program
{
    static void Main(string [] args)
    {
        License.LicenseKey = "License-Key";
        // HTML content for the report
        string htmlContent = "<html><body><h1>Sample Report</h1><p>This is a sample report content.</p></body></html>";
        // Using BasicReportGenerator
        BasicReportGenerator basicReportGenerator = new BasicReportGenerator();
        var basicPdf = basicReportGenerator.GenerateReport(htmlContent);
        basicPdf.SaveAs("basic_report.pdf");
        // Using CustomReportGenerator
        CustomReportGenerator customReportGenerator = new CustomReportGenerator();
        var customPdf = customReportGenerator.GenerateReport(htmlContent);
        customPdf.SaveAs("custom_report.pdf");
        Console.WriteLine("PDF reports generated successfully.");
    }
}

In this example, BasicReportGenerator has a method GenerateReport that takes HTML content and generates a PDF document using IronPDF. The CustomReportGenerator class, which inherits from BasicReportGenerator, overrides the GenerateReport method to add a custom header to the PDF after it's been generated by the base method. Here is the custom report generated by the code:

C# Object Oriented (How It Works For Developers): Figure 3 - The custom PDF generated from the code example, showcasing the OOP methods discussed in the article

Conclusion

C# Object Oriented (How It Works For Developers): Figure 4 - IronPDF licensing page

By understanding and applying the basic principles of OOP, beginners can take significant steps towards mastering C# and developing robust software solutions. Inheritance and polymorphism allow for code reuse and flexibility, letting new classes build upon existing structures and functionalities. Abstraction and encapsulation ensure that classes only expose what is necessary to the outside world, keeping the internal workings private and safe from unintended use. You can try the IronPDF free trial for PDF generation in C#, which is available starting from liteLicense.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.
< PREVIOUS
C# Action (How It Works For Developers)
NEXT >
C# String.Join (How It Works For Developers)