C# Object Oriented (How It Works For Developers)
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.

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.

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:

Conclusion

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.
Frequently Asked Questions
How can I apply object-oriented programming principles in C#?
In C#, you can apply object-oriented programming principles by defining classes and objects to model real-world entities. Use inheritance to extend classes, polymorphism to allow for method overriding, and encapsulation to protect data, thereby creating modular and maintainable code.
What is the role of abstraction in C# programming?
Abstraction in C# allows developers to simplify complex systems by providing a clear separation between abstract, high-level concepts and concrete implementations. Abstract classes and interfaces are used to define a blueprint for other classes, ensuring a consistent structure and behavior across different parts of an application.
How can I create a PDF report using object-oriented principles in C#?
You can create a PDF report in C# by using the IronPDF library, which allows you to generate PDF documents from HTML content. By utilizing object-oriented principles, you can create a base class for report generation and extend it with specific functionalities, like adding custom headers or footers, in derived classes.
What are the advantages of using encapsulation in C#?
Encapsulation in C# offers the advantage of protecting an object's data by restricting access to its internal components. This is achieved using access modifiers, which help maintain data integrity and prevent unintended interference from other parts of a program.
How do I implement polymorphism in a C# application?
In C#, polymorphism can be implemented by using method overriding in derived classes. This allows you to define methods in a base class and override them in derived classes, providing flexibility and allowing objects to be treated as instances of their base class.
How can I extend the functionality of a PDF library in C#?
You can extend the functionality of a PDF library like IronPDF by creating custom classes that implement additional features. For example, you can create a class that inherits from a base PDF generation class and add methods to customize the appearance or content of PDF pages.
Can you provide a coding example using inheritance in C#?
A coding example of inheritance in C# might involve defining a base class, `Vehicle`, with properties like `Speed` and `Fuel`. A derived class, `Car`, could extend `Vehicle` and add specific features like `NumberOfDoors`. This demonstrates how derived classes can inherit and extend the functionality of base classes.
How does IronPDF integrate with object-oriented programming in C#?
IronPDF integrates with object-oriented programming in C# by allowing developers to create classes that encapsulate PDF generation logic. You can define base classes for common PDF operations and extend them with specific functionality, such as adding watermarks or custom formatting, using inheritance and polymorphism.









