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

C# Primary Constructor (How It Works For Developers)

In the Object-oriented landscape of C# programming, the introduction of Primary Constructors brings a new level of elegance and simplicity to the language. Primary constructors, alongside features such as interceptors and collection expressions, emerged in C# 12 as a powerful feature, offering a more concise syntax for declaring constructors with parameters. You can explore Primary constructors in depth on the Microsoft C# guide.

In this article, we'll learn how to use C# 12 Primary Constructors efficiently, also exploring their functionality, use cases, and how they transform the way developers approach class initialization.

Understanding the Basics: Constructors in C#

Constructors play a pivotal role in object-oriented programming, serving as the blueprint for initializing objects. Traditionally, C# developers have used the default constructor or parameterized constructors to set up the initial state of their classes. However, the introduction of Primary Constructors adds a more streamlined approach to this essential aspect of C# development.

The Essence of Primary Constructors

A Primary Constructor in C# is a concise way to declare and initialize properties directly within the class declaration. It simplifies the process of defining and assigning values to properties, offering a more declarative and readable syntax.

Benefits of Primary Constructors

  1. Conciseness: Primary constructors provide a succinct syntax, reducing boilerplate code and enhancing readability.
  2. Scoping: Unlike traditional constructors, parameters in primary constructors are in scope throughout the entire class or struct, offering flexibility in their usage.
  3. Default Values: Default parameter values simplify object creation, making it more convenient for developers.

Declaring a Primary Constructor

The syntax for a Primary Constructor involves declaring the properties directly in the class header. Let's consider a basic Person class example:

public class Person(string name, int age)
{
    public string Name { get; } = name;
    public int Age { get; } = age;
    public override string ToString() => $"Name: {Name}, Age: {Age}";
}
public class Person(string name, int age)
{
    public string Name { get; } = name;
    public int Age { get; } = age;
    public override string ToString() => $"Name: {Name}, Age: {Age}";
}
$vbLabelText   $csharpLabel

In the above code snippet, the Person class has a Primary Constructor that initializes the instance member Name and instance member Age properties. The constructor parameters are declared with the class or struct name, and at the time of defining public properties, the parameter values are assigned to them.

Example 1: Immutable Point in 2D Space

public readonly struct Point(double x, double y)
{
    public double X { get; } = x;
    public double Y { get; } = y;
    public double Magnitude => Math.Sqrt(X * X + Y * Y);
}
public readonly struct Point(double x, double y)
{
    public double X { get; } = x;
    public double Y { get; } = y;
    public double Magnitude => Math.Sqrt(X * X + Y * Y);
}
$vbLabelText   $csharpLabel

In this example, the primary constructor for the Point struct initializes X and Y properties, showcasing how concise and expressive the syntax can be.

Example 2: Configurable Logger with Default Settings

public class Logger(string filePath = "log.txt", LogLevel level = LogLevel.Info)
{
    private readonly string _filePath = filePath;
    private readonly LogLevel _level = level;

    public void Log(string message)
    {
        // Actual logging implementation using _filePath and _level
    }
}
public class Logger(string filePath = "log.txt", LogLevel level = LogLevel.Info)
{
    private readonly string _filePath = filePath;
    private readonly LogLevel _level = level;

    public void Log(string message)
    {
        // Actual logging implementation using _filePath and _level
    }
}
$vbLabelText   $csharpLabel

Here, the primary constructor for the Logger class provides default values for filePath and level, making it flexible and easy to use while maintaining configurability.

Example 3: Dependency Injection

public interface IService
{
    Distance GetDistance();
}

public class ExampleController(IService service) : ControllerBase
{
    public ActionResult<Distance> Get() => service.GetDistance();
}
public interface IService
{
    Distance GetDistance();
}

public class ExampleController(IService service) : ControllerBase
{
    public ActionResult<Distance> Get() => service.GetDistance();
}
$vbLabelText   $csharpLabel

Primary constructors suit dependency injection scenarios. In this example, a controller class indicates its dependencies, enhancing maintainability and facilitating unit testing.

Example 4: Building a Geometric Shape Hierarchy

public abstract class Shape(double width, double height)
{
    public double Width { get; } = width;
    public double Height { get; } = height;
    public abstract double CalculateArea();
}

public class Rectangle(double width, double height) : Shape(width, height)
{
    public override double CalculateArea() => Width * Height;
}

public class Circle : Shape
{
    public Circle(double radius) : base(radius * 2, radius * 2) { }
    public override double CalculateArea() => Math.PI * Math.Pow(Width / 2, 2);
}
public abstract class Shape(double width, double height)
{
    public double Width { get; } = width;
    public double Height { get; } = height;
    public abstract double CalculateArea();
}

public class Rectangle(double width, double height) : Shape(width, height)
{
    public override double CalculateArea() => Width * Height;
}

public class Circle : Shape
{
    public Circle(double radius) : base(radius * 2, radius * 2) { }
    public override double CalculateArea() => Math.PI * Math.Pow(Width / 2, 2);
}
$vbLabelText   $csharpLabel

In this example, the primary constructor in the Shape class forms the foundation for a geometric shape hierarchy. Subclasses like Rectangle and Circle leverage the primary constructor for consistent initialization. The Rectangle class itself declares the primary constructor and passes the captured primary constructor parameters to the Shape class primary parameters. The Circle class showcases flexibility by defining its constructor within the whole class and then passing its parameters as default values for the Shape constructor using the base keyword.

Introducing IronPDF

IronPDF is a versatile C# library that empowers developers to create, manipulate, and convert PDF files effortlessly. Whether you're generating invoices, reports, or any other document, IronPDF allows you to seamlessly convert HTML content into polished and professional PDFs directly within your C# application.

IronPDF is a handy tool for developers that lets them turn webpages, URLs, and HTML to PDF. The best part is that the PDFs look just like the original web pages, with all the formatting and styling preserved. It's perfect for creating PDFs from web content like reports and invoices.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
$vbLabelText   $csharpLabel

C# Primary Constructor (How It Works For Developer): Figure 1 - IronPDF webpage

Installing IronPDF: A Quick Start

To incorporate IronPDF into your C# project, begin by installing the IronPDF NuGet package. Execute the following command in your Package Manager Console:

Install-Package IronPdf

Alternatively, locate "IronPDF" in the NuGet Package Manager and proceed with the installation from there.

C# Primary Constructor (How It Works For Developer): Figure 2 - Searching for the IronPDF package in the NuGet package manager browser

Generating PDFs with IronPDF

Creating a PDF using IronPDF is a streamlined process. Consider the following example:

var htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>";
// Create a new PDF document
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(htmlContent).SaveAs("C:/GeneratedDocument.pdf");
var htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>";
// Create a new PDF document
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(htmlContent).SaveAs("C:/GeneratedDocument.pdf");
$vbLabelText   $csharpLabel

In this example, IronPDF is utilized to render HTML content into a PDF document, subsequently saved to the specified location. For more details on creating and manipulating PDFs in C#, please visit this complete tutorial link, and to explore more please visit this documentation page.

C# Primary Constructors: A Class Initialization Revolution

C# Primary Constructors offer a declarative and streamlined approach to initializing class properties directly within the class declaration. Let's explore whether this elegant feature can be seamlessly integrated with IronPDF.

Integration of C# Primary Constructors with IronPDF

While C# Primary Constructors are primarily a language feature focused on class initialization, their direct integration with IronPDF may not be a common use case. IronPDF's core functionality lies in the generation and manipulation of PDF documents, and the specifics of class initialization might not directly align with this workflow.

However, developers can leverage C# Primary Constructors when defining custom classes or structures related to IronPDF configurations or data models. For instance, if your application requires a specific class structure to manage PDF-related settings or configurations, C# Primary Constructors can be a valuable tool for initializing these classes concisely.

public class PdfGenerationSettings(string title, bool includeHeader, bool includeFooter)
{
    public string Title { get; } = title;
    public bool IncludeHeader { get; } = includeHeader;
    public bool IncludeFooter { get; } = includeFooter;
    // Additional properties...
}

// Usage with IronPDF
var pdfSettings = new PdfGenerationSettings("My PDF Title", true, false);
var renderOptions = new ChromePdfRenderOptions
{
    PaperSize = IronPdf.Rendering.PdfPaperSize.A4,
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 10,
    MarginRight = 10,
    Title = pdfSettings.Title
};
// Apply settings from PdfGenerationSettings
if (pdfSettings.IncludeHeader)
{
    renderOptions.TextHeader = new TextHeaderFooter
    {
        CenterText = "Page {page} of {total-pages}",
        DrawDividerLine = true
    };
}
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderingOptions = renderOptions;
pdfDocument.RenderHtmlAsPdf("<html><body><h1>Hello, IronPDF!</h1></body></html>").SaveAs("CustomizedDocument.pdf");
public class PdfGenerationSettings(string title, bool includeHeader, bool includeFooter)
{
    public string Title { get; } = title;
    public bool IncludeHeader { get; } = includeHeader;
    public bool IncludeFooter { get; } = includeFooter;
    // Additional properties...
}

// Usage with IronPDF
var pdfSettings = new PdfGenerationSettings("My PDF Title", true, false);
var renderOptions = new ChromePdfRenderOptions
{
    PaperSize = IronPdf.Rendering.PdfPaperSize.A4,
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 10,
    MarginRight = 10,
    Title = pdfSettings.Title
};
// Apply settings from PdfGenerationSettings
if (pdfSettings.IncludeHeader)
{
    renderOptions.TextHeader = new TextHeaderFooter
    {
        CenterText = "Page {page} of {total-pages}",
        DrawDividerLine = true
    };
}
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderingOptions = renderOptions;
pdfDocument.RenderHtmlAsPdf("<html><body><h1>Hello, IronPDF!</h1></body></html>").SaveAs("CustomizedDocument.pdf");
$vbLabelText   $csharpLabel

In this example, the PdfGenerationSettings class utilizes a C# Primary Constructor to initialize properties related to PDF generation settings, which can later be used to figure out which rendering options to add and which to skip. The output contains a header text and title as it was set using the primary constructor parameter.

C# Primary Constructor (How It Works For Developer): Figure 3 - Output PDF from the code example above

Conclusion

In conclusion, Primary Constructors in C# present a refined and expressive approach to class initialization. Their declarative syntax enhances code readability, promotes immutability, and simplifies the process of creating objects with default values. Whether you're defining properties, enforcing immutability, or embracing default values, Primary Constructors empower developers to master the art of class initialization in the dynamic world of C# programming.

While the direct integration of C# Primary Constructors with IronPDF might not be the main focus, these two elements can work together harmoniously. C# Primary Constructors enhance the clarity and simplicity of class initialization, making them valuable for defining structures or configurations related to IronPDF workflows.

Leverage the power of IronPDF for robust PDF generation, and employ C# Primary Constructors where class initialization elegance is paramount. This dynamic duo empowers you to navigate the complexities of document generation with creativity and efficiency in the vibrant world of C# programming.

IronPDF offers a free trial and its lite license starts from $799.

자주 묻는 질문

기본 생성자는 어떻게 C# 코드를 더 간결하게 만들까요?

기본 생성자를 사용하면 클래스 선언 내에서 직접 프로퍼티를 선언하고 초기화할 수 있으므로 상용구 코드의 양이 줄어들고 가독성이 향상됩니다.

C# 12에 새로 도입된 기능은 무엇인가요?

C# 12에서는 개발자에게 보다 간결하고 강력한 구문 옵션을 제공하는 기본 생성자, 인터셉터 및 컬렉션 표현식을 소개합니다.

기본 생성자를 불변 데이터 구조와 함께 사용할 수 있나요?

예, 기본 생성자는 생성자 내에서 직접 읽기 전용 프로퍼티를 초기화할 수 있으므로 불변 데이터 구조에 적합합니다.

C#을 사용하여 HTML 콘텐츠를 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF의 ChromePdfRenderer 클래스를 사용하여 HTML 콘텐츠를 PDF로 변환하여 출력 문서에서 서식과 스타일을 유지할 수 있습니다.

PDF 생성에 IronPDF를 사용하면 어떤 이점이 있나요?

IronPDF는 C#으로 PDF 파일을 만들고 조작할 수 있는 강력한 플랫폼을 제공하며 HTML에서 PDF로 변환, PDF 병합 및 세부 스타일 보존과 같은 기능을 지원합니다.

기본 생성자는 종속성 주입을 어떻게 향상하나요?

기본 생성자는 생성자 매개변수에 클래스 종속성을 명확하게 표시하여 종속성 그래프의 설정 및 유지 관리를 간소화함으로써 종속성 주입을 향상시킵니다.

기본 생성자를 PDF 문서 생성과 어떻게 통합할 수 있나요?

기본 생성자는 IronPDF와 같은 라이브러리를 사용할 때 PDF 설정과 관련된 구성 클래스 또는 구조를 초기화하여 설정 프로세스를 간소화하는 데 사용할 수 있습니다.

기본 생성자가 실제로 사용되는 예시에는 어떤 것이 있나요?

실제 예시에는 명확성과 간결함이 필수적인 기하학적 도형 계층 구조의 초기화 및 종속성 주입 시나리오가 포함됩니다.

개발자는 프로젝트에서 IronPDF를 어떻게 사용할 수 있나요?

개발자는 패키지 관리자 콘솔 또는 NuGet 패키지 관리자를 통해 IronPDF NuGet 패키지를 설치하고 구현에 대한 자세한 내용은 종합 문서를 참조할 수 있습니다.

문서 생성 워크플로우에서 IronPDF는 어떤 역할을 하나요?

IronPDF는 개발자가 C#에서 PDF를 쉽게 생성, 변환 및 조작할 수 있도록 하여 문서 생성 워크플로우를 개선하고 다른 C# 기능과의 원활한 통합을 지원합니다.

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

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

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