Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
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#.
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.
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 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 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 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");
}
}
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 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.
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.
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.
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:
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
.