푸터 콘텐츠로 바로가기
.NET 도움말

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();
    }
}
$vbLabelText   $csharpLabel

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();
    }
}
$vbLabelText   $csharpLabel

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");
    }
}
$vbLabelText   $csharpLabel

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");
    }
}
$vbLabelText   $csharpLabel

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; }
}
$vbLabelText   $csharpLabel

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.");
        }
    }
}
$vbLabelText   $csharpLabel

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.");
    }
}
$vbLabelText   $csharpLabel

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.

자주 묻는 질문

C#에서 객체 지향 프로그래밍 원칙을 적용하려면 어떻게 해야 하나요?

C#에서는 클래스와 객체를 정의하여 실제 엔티티를 모델링함으로써 객체 지향 프로그래밍 원칙을 적용할 수 있습니다. 상속을 사용하여 클래스를 확장하고, 다형성을 사용하여 메서드 재정의가 가능하며, 캡슐화를 통해 데이터를 보호하여 모듈화되고 유지 관리가 쉬운 코드를 만들 수 있습니다.

C# 프로그래밍에서 추상화의 역할은 무엇인가요?

C#의 추상화를 통해 개발자는 추상적이고 높은 수준의 개념과 구체적인 구현을 명확하게 구분하여 복잡한 시스템을 단순화할 수 있습니다. 추상 클래스와 인터페이스는 다른 클래스에 대한 청사진을 정의하는 데 사용되어 애플리케이션의 여러 부분에 걸쳐 일관된 구조와 동작을 보장합니다.

C#에서 객체 지향 원칙을 사용하여 PDF 보고서를 만들려면 어떻게 해야 하나요?

HTML 콘텐츠로부터 PDF 문서를 생성할 수 있는 IronPDF 라이브러리를 사용하여 C#으로 PDF 보고서를 만들 수 있습니다. 객체 지향 원칙을 활용하여 보고서 생성을 위한 기본 클래스를 만들고 파생 클래스에서 사용자 지정 머리글 또는 바닥글 추가와 같은 특정 기능으로 확장할 수 있습니다.

C#에서 캡슐화를 사용하면 어떤 이점이 있나요?

C#의 캡슐화는 내부 컴포넌트에 대한 액세스를 제한하여 객체의 데이터를 보호할 수 있는 이점을 제공합니다. 이는 액세스 수정자를 사용하여 데이터 무결성을 유지하고 프로그램의 다른 부분으로부터 의도하지 않은 간섭을 방지하는 데 도움이 됩니다.

C# 애플리케이션에서 다형성을 구현하려면 어떻게 해야 하나요?

C#에서는 파생 클래스에서 메서드 오버라이딩을 사용하여 다형성을 구현할 수 있습니다. 이를 통해 기본 클래스에서 메서드를 정의하고 파생 클래스에서 재정의하여 유연성을 제공하고 개체를 기본 클래스의 인스턴스로 취급할 수 있습니다.

C#에서 PDF 라이브러리의 기능을 확장하려면 어떻게 해야 하나요?

추가 기능을 구현하는 사용자 정의 클래스를 생성하여 IronPDF와 같은 PDF 라이브러리의 기능을 확장할 수 있습니다. 예를 들어 기본 PDF 생성 클래스를 상속하는 클래스를 만들고 메서드를 추가하여 PDF 페이지의 모양이나 내용을 사용자 지정할 수 있습니다.

C#에서 상속을 사용한 코딩 예제를 제공할 수 있나요?

C#에서 상속의 코딩 예로는 '속도' 및 '연료' 등의 속성을 가진 기본 클래스인 'Vehicle'을 정의하는 것을 들 수 있습니다. 파생 클래스인 `Car`는 `Vehicle`을 확장하고 `NumberOfDoors`와 같은 특정 기능을 추가할 수 있습니다. 이는 파생 클래스가 어떻게 기본 클래스의 기능을 상속하고 확장할 수 있는지 보여줍니다.

IronPDF는 C#의 객체 지향 프로그래밍과 어떻게 통합되나요?

IronPDF는 개발자가 PDF 생성 로직을 캡슐화하는 클래스를 만들 수 있도록 하여 C#의 객체 지향 프로그래밍과 통합됩니다. 일반적인 PDF 작업을 위한 기본 클래스를 정의하고 상속 및 다형성을 사용하여 워터마크 추가 또는 사용자 정의 서식 지정과 같은 특정 기능으로 확장할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.