.NET 도움말 C# Params (How It Works For Developers) 커티스 차우 업데이트됨:6월 22, 2025 다운로드 IronPDF NuGet 다운로드 DLL 다운로드 윈도우 설치 프로그램 무료 체험 시작하기 LLM용 사본 LLM용 사본 LLM용 마크다운 형식으로 페이지를 복사하세요 ChatGPT에서 열기 ChatGPT에 이 페이지에 대해 문의하세요 제미니에서 열기 제미니에게 이 페이지에 대해 문의하세요 Grok에서 열기 Grok에게 이 페이지에 대해 문의하세요 혼란 속에서 열기 Perplexity에게 이 페이지에 대해 문의하세요 공유하다 페이스북에 공유하기 트위터에 공유하기 LinkedIn에 공유하기 URL 복사 이메일로 기사 보내기 The params keyword in C# is a powerful feature in .NET that allows a method to accept a variable number of arguments. This can significantly simplify the syntax when calling methods that require a varying number of parameters. In this comprehensive guide, we will explore the params keyword in C#, its syntax, use cases, and best practices. Later in this article, we will introduce the IronPDF library from Iron Software and explain how to use the params keyword and IronPDF to generate PDFs. What is the C# Params Argument Type? In the realm of C#, methods typically adhere to a predetermined set of parameters. Nevertheless, there exist situations where one might find themselves uncertain about the precise number of arguments destined for a method. Enter the "params" keyword, a solution that enables the specification of a method parameter capable of accommodating an array of arguments. This functionality proves invaluable when the developer is unsure about the exact number of arguments in advance, facilitating the passage of an indeterminate or optional number of parameters, all of the same type, within a method declaration. public class ParamsExample { // Method accepting a variable number of string arguments using the params keyword public void PrintMessages(params string[] messages) { foreach (var message in messages) { Console.WriteLine(message); } } } // Usage class Program { public static void Main() { var example = new ParamsExample(); example.PrintMessages("Hello", "World", "!"); } // More examples public static void AddItemsToShoppingBasket(params string[] items) { // Implementation to add items to a shopping basket } public static void AddItemsSumToShoppingBasket(params int[] sum) // Using params with int { // Implementation to add sum of items to the shopping basket } } public class ParamsExample { // Method accepting a variable number of string arguments using the params keyword public void PrintMessages(params string[] messages) { foreach (var message in messages) { Console.WriteLine(message); } } } // Usage class Program { public static void Main() { var example = new ParamsExample(); example.PrintMessages("Hello", "World", "!"); } // More examples public static void AddItemsToShoppingBasket(params string[] items) { // Implementation to add items to a shopping basket } public static void AddItemsSumToShoppingBasket(params int[] sum) // Using params with int { // Implementation to add sum of items to the shopping basket } } $vbLabelText $csharpLabel The AddItemsToShoppingBasket method can be invoked with a variable number of arguments of string parameters. The params keyword simplifies the syntax for the method call by allowing developers to pass the optional parameters directly, without explicitly creating an array input. class Program { public static void Main() { AddItemsToShoppingBasket("cake", "pizza", "cold drink"); AddItemsToShoppingBasket("snacks", "burger"); AddItemsToShoppingBasket(); // Valid even with zero parameters, using default value } } class Program { public static void Main() { AddItemsToShoppingBasket("cake", "pizza", "cold drink"); AddItemsToShoppingBasket("snacks", "burger"); AddItemsToShoppingBasket(); // Valid even with zero parameters, using default value } } $vbLabelText $csharpLabel Considerations and Best Practices Position Params at the End of Parameter List: A recommended practice is to situate the params parameter at the conclusion of the method's parameter list. This practice fosters clarity, mitigating confusion during method calls. Parameters requiring explicit values should precede the params for effective organization. Explicitly Specify Non-params Parameters: When invoking a method with params, ensure explicit provision of values for non-params parameters. This practice prevents ambiguity and guarantees the accurate invocation of the method with the requisite number of arguments. Exercise Caution to Prevent Ambiguity: Vigilance is key when utilizing params in methods with multiple overloads or parameters of the same type. The compiler may grapple with determining the appropriate method to invoke, potentially resulting in ambiguity errors. Explore Alternative Approaches: While params offers convenience, consider alternative methods in certain scenarios. Utilizing collections such as List<T> could be preferable for enhanced functionality or when passing named parameters aligns with your objectives. Apply Judiciously to Relevant Scenarios: Deploy params judiciously in scenarios where the parameter count is variable and can fluctuate across distinct method calls. Reserve its usage for situations where the number of parameters is unpredictable, steering clear of its application when the parameter count is fixed and known. One-Dimensional Array for the Parameter Type AddItemsToShoppingBasket can also be used by calling it with a one-dimensional array. class Program { public static void Main() { var items = new string[] { "cold drink", "snack", "roll" }; // 1D string array AddItemsToShoppingBasket(items); // Works as expected AddItemsToShoppingBasket("cold drink", "coke", "roll"); // Similar result to the above line } } class Program { public static void Main() { var items = new string[] { "cold drink", "snack", "roll" }; // 1D string array AddItemsToShoppingBasket(items); // Works as expected AddItemsToShoppingBasket("cold drink", "coke", "roll"); // Similar result to the above line } } $vbLabelText $csharpLabel Pass a Comma-Separated Array of Arguments of the Same Type AddItemsToShoppingBasket can be called by passing a list/array of variables in the method call like below. class Program { public static void Main() { // Example method signature AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // Comma separated values AddItemsToShoppingBasket("snacks"); } } class Program { public static void Main() { // Example method signature AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // Comma separated values AddItemsToShoppingBasket("snacks"); } } $vbLabelText $csharpLabel Pass an Array of the Defined Type The array should contain the same type defined in the params method; otherwise, an error is thrown. // Example that results in an error AddItemsToShoppingBasket("snacks", 2, "burger"); // Error due to type mismatch AddItemsToShoppingBasket(2, 3, 4); // Error since params type is string // Example that results in an error AddItemsToShoppingBasket("snacks", 2, "burger"); // Error due to type mismatch AddItemsToShoppingBasket(2, 3, 4); // Error since params type is string $vbLabelText $csharpLabel A syntax error occurs if there is a type mismatch from the defined params in the method. Always the Last Parameter in the Method No additional parameters are permitted after the params parameter in a method signature. Only one params argument is permitted in a method parameters declaration. Defining it incorrectly leads to compilation errors. class Program { static void Main(string[] args) { // Example 1 public static void AddItemsToShoppingBasket(double total, params string[] items) { // Works fine as `params` is the last parameter } // Example 2, error scenario public static void AddItemsToShoppingBasket(params string[] items, decimal total, int total) { // Error: `params` keyword must be the last parameter } } } class Program { static void Main(string[] args) { // Example 1 public static void AddItemsToShoppingBasket(double total, params string[] items) { // Works fine as `params` is the last parameter } // Example 2, error scenario public static void AddItemsToShoppingBasket(params string[] items, decimal total, int total) { // Error: `params` keyword must be the last parameter } } } $vbLabelText $csharpLabel Only One params Keyword Only one params parameter in a method signature is allowed. The compiler throws an error if more than one params keyword is found in the method signature. class Program { static void Main(string[] args) { public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity) { // Compiler Error: Only one params keyword is allowed in the method signature } } } class Program { static void Main(string[] args) { public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity) { // Compiler Error: Only one params keyword is allowed in the method signature } } } $vbLabelText $csharpLabel You Can Pass No Arguments If a method has a parameter with the params keyword, it can be called without any arguments, and the compiler won't throw an error. AddItemsToShoppingBasket(); // Works as expected AddItemsToShoppingBasket(); // Works as expected $vbLabelText $csharpLabel For any parameter with a params argument, it is considered an optional parameter and can be invoked without passing parameters. Code Example Create a new Console Application. Open Visual Studio, create a new project, and select the console application type. Now add the below code. using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<string> cart = new List<string>(); void AddItemsToShoppingBasket(params string[] samples) { for (int i = 0; i < samples.Length; i++) { cart.Add(samples[i]); } } // Caller code Console.WriteLine("Enter the cart items as comma separated values"); var itemsString = Console.ReadLine(); if (itemsString != null) { var items = itemsString.Split(",").ToArray(); AddItemsToShoppingBasket(items); } AddItemsToShoppingBasket("Sample1", "Sample2"); Console.WriteLine("-------------------------------------------------------"); Console.WriteLine("Display Cart"); foreach (var item in cart) { Console.WriteLine(item); } } } using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<string> cart = new List<string>(); void AddItemsToShoppingBasket(params string[] samples) { for (int i = 0; i < samples.Length; i++) { cart.Add(samples[i]); } } // Caller code Console.WriteLine("Enter the cart items as comma separated values"); var itemsString = Console.ReadLine(); if (itemsString != null) { var items = itemsString.Split(",").ToArray(); AddItemsToShoppingBasket(items); } AddItemsToShoppingBasket("Sample1", "Sample2"); Console.WriteLine("-------------------------------------------------------"); Console.WriteLine("Display Cart"); foreach (var item in cart) { Console.WriteLine(item); } } } $vbLabelText $csharpLabel Output Introducing IronPDF IronPDF C# PDF library from Iron Software is a versatile library that can read, write, and manage PDF documents in C#. It supports all kinds of modern application development like Mobile, Website, Desktop, Docker, etc. And also supports different OS like Windows, Linux, Unix, etc. It does not depend on native OS methods. IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents. 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 Installation IronPDF library can be installed using the NuGet package manager console with the below command or using the Visual Studio package manager. Install-Package IronPdf Using IronPDF to Generate a PDF Now we will use IronPDF to generate the PDF document from the above example. using System; using System.Collections.Generic; using System.Linq; using IronPdf; class Program { public static void Main() { List<string> cart = new List<string>(); void AddItemsToShoppingBasket(params string[] items) { for (int i = 0; i < items.Length; i++) { cart.Add(items[i]); } } // Take input from console Console.WriteLine("Enter the cart items as comma separated values"); var itemsString = Console.ReadLine(); // Read the items if (itemsString != null) { var items = itemsString.Split(",").ToArray(); AddItemsToShoppingBasket(items); } // Add to cart AddItemsToShoppingBasket("Sample1", "Sample2"); Console.WriteLine("------------------------------------------------"); Console.WriteLine("Display Cart"); Console.WriteLine("------------------------------------------------"); string name = "Sam"; var count = cart.Count; string content = $@"<!DOCTYPE html> <html> <body> <h1>Hello, {name}!</h1> <p>You have {count} items in the cart.</p> " + string.Join("\n", cart.Select(x => $"<p>{x}</p>")) + @" </body> </html>"; // Create a new PDF document var pdfDoc = new ChromePdfRenderer(); pdfDoc.RenderHtmlAsPdf(content).SaveAs("cart.pdf"); } } using System; using System.Collections.Generic; using System.Linq; using IronPdf; class Program { public static void Main() { List<string> cart = new List<string>(); void AddItemsToShoppingBasket(params string[] items) { for (int i = 0; i < items.Length; i++) { cart.Add(items[i]); } } // Take input from console Console.WriteLine("Enter the cart items as comma separated values"); var itemsString = Console.ReadLine(); // Read the items if (itemsString != null) { var items = itemsString.Split(",").ToArray(); AddItemsToShoppingBasket(items); } // Add to cart AddItemsToShoppingBasket("Sample1", "Sample2"); Console.WriteLine("------------------------------------------------"); Console.WriteLine("Display Cart"); Console.WriteLine("------------------------------------------------"); string name = "Sam"; var count = cart.Count; string content = $@"<!DOCTYPE html> <html> <body> <h1>Hello, {name}!</h1> <p>You have {count} items in the cart.</p> " + string.Join("\n", cart.Select(x => $"<p>{x}</p>")) + @" </body> </html>"; // Create a new PDF document var pdfDoc = new ChromePdfRenderer(); pdfDoc.RenderHtmlAsPdf(content).SaveAs("cart.pdf"); } } $vbLabelText $csharpLabel In the above code, we are generating an HTML document for cart items and then saving it as a PDF document using IronPDF. Output Licensing (Free Trial Available) IronPDF requires a license key to work in production. A trial key can be obtained from the license page here. Place the key in appsettings.json. "IronPdf.LicenseKey": "your license key" Provide your email ID to get a trial license delivered to your email ID. Conclusion The params keyword in C# offers a flexible way to handle methods that require a variable number of parameters. It simplifies the method calls and makes the code more readable and maintainable. Together with IronPDF, it is a great combination of skills for any programmer to write clean code. 자주 묻는 질문 C#에서 'params' 키워드는 무엇인가요? C#의 'params' 키워드를 사용하면 메서드가 다양한 수의 인수를 허용하여 다양한 매개변수 수를 가진 메서드를 호출하는 구문을 단순화할 수 있습니다. 메서드 서명에서 'params' 키워드는 어떻게 작동하나요? 메서드 서명에서는 매개변수 유형과 매개변수 이름 앞에 'params' 키워드를 사용하여 메서드가 해당 유형의 인수를 배열로 얼마든지 받아들일 수 있도록 합니다. 'params'가 있는 메서드는 인수를 0으로 받을 수 있나요? 예, 'params' 매개변수가 있는 메서드는 인자 없이 호출할 수 있으며, 'params' 매개변수는 선택 사항으로 취급됩니다. C#에서 'params'를 사용하는 모범 사례는 무엇인가요? 모범 사례로는 매개변수 목록의 끝에 'params' 매개변수를 배치하고, 'params'가 아닌 매개변수는 명시적으로 지정하며, 매개변수 수가 달라질 수 있는 경우에만 신중하게 사용하는 것 등이 있습니다. C# 메서드에 둘 이상의 '매개변수'가 있을 수 있나요? 아니요, C# 메서드에는 'params' 매개변수가 하나만 있을 수 있으며, 이 매개변수는 메서드 서명의 마지막 매개변수여야 합니다. '매개변수'를 사용하면 C#에서 메서드 유연성을 어떻게 향상시킬 수 있나요? C# 메서드에서 '매개변수'를 사용하면 개발자가 동적 매개변수를 처리할 수 있는 보다 유연한 코드를 작성할 수 있으므로 유지 관리 및 확장이 더 쉬워집니다. 문서 생성을 위해 'params' 키워드를 C# 라이브러리와 어떻게 결합할 수 있나요? 'params' 키워드는 C# 라이브러리와 함께 사용하여 다양한 콘텐츠의 PDF 생성 등 문서 생성 작업을 위한 유연한 매개변수 전달에 사용할 수 있습니다(예: IronPDF를 사용한 다양한 콘텐츠의 PDF 생성). C# 라이브러리를 사용하여 HTML을 PDF로 변환하려면 어떻게 해야 하나요? IronPDF와 같은 C# 라이브러리를 사용하여 HTML 문자열의 경우 RenderHtmlAsPdf 또는 HTML 파일의 경우 RenderHtmlFileAsPdf와 같은 메서드를 사용하여 HTML을 PDF로 변환할 수 있습니다. C#에서 'params' 키워드의 일반적인 사용 사례에는 어떤 것이 있나요? 'params' 키워드의 일반적인 사용 사례로는 메시지 로깅, 수학 연산, 문자열 출력 작성 등 다양한 입력을 처리해야 하는 메서드가 있습니다. 프로젝트에서 PDF 조작을 위한 C# 라이브러리를 어떻게 통합하나요? IronPDF와 같은 PDF 조작용 C# 라이브러리를 통합하려면 NuGet을 사용하여 닷넷 추가 패키지 [라이브러리 이름] 명령으로 설치한 다음 해당 API를 사용하여 PDF 작업을 수행할 수 있습니다. 커티스 차우 지금 바로 엔지니어링 팀과 채팅하세요 기술 문서 작성자 커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다. 커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다. 관련 기사 업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기 업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기 업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기 C# PostgreSQL (How It Works For Developers)C# Enums (How It Works For Developers)
업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기
업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기
업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기