.NET HELP

C# Object Oriented (How It Works For Developers)

Published 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();
    }
}
Public Class Car ' A class declared as 'Car' defines its structure and behavior.
	Public Name As String
	Public Color As String
	Public Sub DisplayInfo()
		Console.WriteLine($"Name: {Name}, Color: {Color}")
	End Sub
End Class
Friend Class Program ' This is the program class, serving as the entry point of a C# program.
	Shared Sub Main(ByVal args() As String)
		Dim myCar As New Car()
		myCar.Name = "Toyota"
		myCar.Color = "Red"
		myCar.DisplayInfo()
	End Sub
End Class
VB   C#

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();
    }
}
Public Class Vehicle
	Public LicensePlate As String
	Public Sub Honk()
		Console.WriteLine("Honking")
	End Sub
End Class
Public Class Truck ' Truck is a child class derived from the Vehicle base class.
	Inherits Vehicle

	Public CargoCapacity As Integer
End Class
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim myTruck As New Truck()
		myTruck.LicensePlate = "ABC123"
		myTruck.CargoCapacity = 5000
		myTruck.Honk()
	End Sub
End Class
VB   C#

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");
    }
}
Public MustInherit Class Shape
	Public MustOverride Sub Draw()
End Class
Public Class Circle
	Inherits Shape

	Public Overrides Sub Draw()
		Console.WriteLine("Drawing a circle")
	End Sub
End Class
VB   C#

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");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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; } 
}
Public Class Person
'INSTANT VB NOTE: The field name was renamed since Visual Basic does not allow fields to have the same name as other class members:
	Private name_Conflict As String ' Private variable, inaccessible outside the class
	Public Property Name() As String ' Public property to access the private variable
		Get
			Return name_Conflict
		End Get
		Set(ByVal value As String)
			name_Conflict = value
		End Set
	End Property
End Class
' Example showing a simple customer class with encapsulated data
Public Class Customer
	Public Property Name() As String
	Public Property Address() As String
End Class
VB   C#

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.");
        }
    }
}
Imports System
Namespace OOPExample
	Public Class Program
		Shared Sub Main(ByVal args() As String)
			Dim myElectricCar As New ElectricCar()
			myElectricCar.Make = "Tesla"
			myElectricCar.Model = "Model 3"
			myElectricCar.BatteryLevel = 100
			myElectricCar.Drive()
			myElectricCar.Charge()
		End Sub
	End Class
	Public MustInherit Class Vehicle
		Public Property Make() As String
		Public Property Model() As String
		Public MustOverride Sub Drive()
	End Class
	Public Class Car
		Inherits Vehicle

		Public Overrides Sub Drive()
			Console.WriteLine($"The {Make} {Model} is driving.")
		End Sub
	End Class
	Public Class ElectricCar
		Inherits Car

		Public Property BatteryLevel() As Integer
		Public Sub Charge()
			Console.WriteLine("Charging the car.")
		End Sub
		Public Overrides Sub Drive()
			Console.WriteLine($"The {Make} {Model} is driving silently.")
		End Sub
	End Class
End Namespace
VB   C#

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.");
    }
}
Imports IronPdf
Public Class BasicReportGenerator
	Public Overridable Function GenerateReport(ByVal htmlContent As String) As PdfDocument
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
		Return pdf
	End Function
End Class
Public Class CustomReportGenerator
	Inherits BasicReportGenerator

	Public Overrides Function GenerateReport(ByVal htmlContent As String) As PdfDocument
		Dim pdf = MyBase.GenerateReport(htmlContent)
		AddCustomHeader(pdf, "Custom Report Header")
		Return pdf
	End Function
	Private Sub AddCustomHeader(ByVal document As PdfDocument, ByVal headerContent As String)
		' Create text header
		Dim textHeader As New TextHeaderFooter With {.CenterText = headerContent}
		document.AddTextHeaders(textHeader)
	End Sub
End Class
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "License-Key"
		' HTML content for the report
		Dim htmlContent As String = "<html><body><h1>Sample Report</h1><p>This is a sample report content.</p></body></html>"
		' Using BasicReportGenerator
		Dim basicReportGenerator As New BasicReportGenerator()
		Dim basicPdf = basicReportGenerator.GenerateReport(htmlContent)
		basicPdf.SaveAs("basic_report.pdf")
		' Using CustomReportGenerator
		Dim customReportGenerator As New CustomReportGenerator()
		Dim customPdf = customReportGenerator.GenerateReport(htmlContent)
		customPdf.SaveAs("custom_report.pdf")
		Console.WriteLine("PDF reports generated successfully.")
	End Sub
End Class
VB   C#

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.

< PREVIOUS
C# Action (How It Works For Developers)
NEXT >
C# String.Join (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >