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

C# Naming Conventions (How It Works For Developers)

Naming conventions are a set of rules and guidelines developers follow to name variables, methods, classes, and other entities consistently. Consistent naming not only enhances code readability but also helps other developers understand and maintain your code. Below, we will walk through the C# naming conventions step by step, focusing on practical usage and examples. Let’s dive right in about naming conventions and the IronPDF library later in the article.

Naming Conventions Overview

Classes and Interfaces

Class names should follow the Pascal Case naming convention. This means each word in the name starts with a capital letter, with no underscores or spaces. Interface names should also follow Pascal Case but start with the prefix I. For example:

public class Customer
{
    public decimal Balance { get; set; }
}

public interface ICustomer
{
    decimal GetBalance();
}
public class Customer
{
    public decimal Balance { get; set; }
}

public interface ICustomer
{
    decimal GetBalance();
}
$vbLabelText   $csharpLabel

Notice how the class name Customer and the interface name ICustomer both follow Pascal Case. The I prefix makes it clear that the ICustomer type is an interface.

Methods

Method names also use the Pascal Case. Every method name should start with a capital letter, and each subsequent word should also start with a capital letter. Here's an example of method definitions:

public decimal CalculateInterest(decimal principal, decimal rate)
{
    return principal * rate;
}
public decimal CalculateInterest(decimal principal, decimal rate)
{
    return principal * rate;
}
$vbLabelText   $csharpLabel

For the entry point method, static void Main(), the convention is the same—use Pascal Case for the method name.

Properties

Like method names, property names also use Pascal Case. Properties should be named to clearly describe what they represent:

public DateTime DateOpened { get; set; }
public decimal Reserves { get; set; }
public DateTime DateOpened { get; set; }
public decimal Reserves { get; set; }
$vbLabelText   $csharpLabel

Local Variables and Method Arguments

Local variables and method arguments should use camel case. This means the first word is in lowercase, and subsequent words start with a capital letter, with no spaces or underscores. This is different from Pascal Case in that the first letter is not capitalized.

public void SelectCustomer(string customerName)
{
    var selectedCustomer = FindCustomer(customerName);
}
public void SelectCustomer(string customerName)
{
    var selectedCustomer = FindCustomer(customerName);
}
$vbLabelText   $csharpLabel

In this example, the local variable selectedCustomer follows the camel case convention, and the method argument customerName is also in camel case.

Method Arguments

The names of method arguments should be descriptive and follow the camel case naming convention. This improves code readability and helps developers understand what each argument represents.

public void AddCustomer(string customerName, DateTime dateOpened)
{
    // Add customer logic
}
public void AddCustomer(string customerName, DateTime dateOpened)
{
    // Add customer logic
}
$vbLabelText   $csharpLabel

Static Members and Fields

Static members in classes, like static fields, constants, and methods, also follow specific naming conventions.

Static Fields

For static fields, the naming convention is to use camel case but with an underscore prefix. This differentiates them from other fields.

private static int _totalCustomers;
private static int _totalCustomers;
$vbLabelText   $csharpLabel

Constants

Constants are typically named using all capital letters, with words separated by underscores to improve readability. For example:

public const int MAX_CUSTOMERS = 100;
public const int MAX_CUSTOMERS = 100;
$vbLabelText   $csharpLabel

Event Handlers

Event handler method names should describe the event they handle, usually by using the On prefix followed by the event name. The parameters for event handler methods typically include the object sender and the event arguments.

private void OnCustomerAdded(object sender, EventArgs e)
{
    // Event handling logic
}
private void OnCustomerAdded(object sender, EventArgs e)
{
    // Event handling logic
}
$vbLabelText   $csharpLabel

In this case, the parameters are named sender and e. Following this naming convention makes your event handlers consistent with industry standards.

Naming Private Fields and Object Initializers

Private fields should follow the camel case convention but with an underscore prefix. This helps distinguish them from local variables and method arguments.

private string _customerName;
private string _customerName;
$vbLabelText   $csharpLabel

When using object initializers, you can assign values directly to properties when creating an instance of a class:

var seattleCustomer = new Customer
{
    Balance = 1000,
    DateOpened = DateTime.Now
};
var seattleCustomer = new Customer
{
    Balance = 1000,
    DateOpened = DateTime.Now
};
$vbLabelText   $csharpLabel

In this example, the property names Balance and DateOpened are in Pascal Case, following the convention for properties.

Exception Handling and Methods

When handling exceptions, method names should still follow Pascal Case conventions. Exception class names should also be in Pascal Case and end with the suffix Exception. For example:

public void ProcessTransaction()
{
    try
    {
        // Transaction logic
    }
    catch (InvalidOperationException ex)
    {
        // Handle exception
    }
}
public void ProcessTransaction()
{
    try
    {
        // Transaction logic
    }
    catch (InvalidOperationException ex)
    {
        // Handle exception
    }
}
$vbLabelText   $csharpLabel

Return Types and Method Definitions

Always ensure that your method definitions have meaningful names and appropriate return types. The return type should be clear from the method signature. Here’s an example:

public decimal CalculateTotalBalance()
{
    return _totalCustomers * balancePerCustomer;
}
public decimal CalculateTotalBalance()
{
    return _totalCustomers * balancePerCustomer;
}
$vbLabelText   $csharpLabel

In this example, the method name CalculateTotalBalance is descriptive and follows the Pascal Case naming convention.

Naming Conventions for C# Constants

In C#, constant names should be all uppercase letters, with words separated by underscores. This makes constants stand out from other variables. Here’s an example:

public const double PI = 3.14159;
public const double PI = 3.14159;
$vbLabelText   $csharpLabel

This convention applies across different types, ensuring that constant names are consistent and easy to recognize in the code.

C# Coding Conventions for Line Breaks and Braces

C# also has coding conventions for line breaks and braces. In C#, each opening brace { should be on the same line as the statement it belongs to, and the closing brace } should be on a new line, aligned with the corresponding statement. Here’s an example:

public void AddCustomer(string customerName)
{
    if (!string.IsNullOrEmpty(customerName))
    {
        _customerName = customerName;
    }
}
public void AddCustomer(string customerName)
{
    if (!string.IsNullOrEmpty(customerName))
    {
        _customerName = customerName;
    }
}
$vbLabelText   $csharpLabel

Using proper formatting makes the code easier to read and follow.

Avoiding Hungarian Notation

In modern C# development, Hungarian Notation, where variable names are prefixed with data types (e.g., strName for a string or intCount for an integer), is discouraged. Instead, use meaningful names that describe the purpose of the variable rather than its data type:

public string CustomerName { get; set; }
public int OrderCount { get; set; }
public string CustomerName { get; set; }
public int OrderCount { get; set; }
$vbLabelText   $csharpLabel

This approach makes the code clearer and more maintainable.

Using IronPDF with Naming Conventions

C# Naming Conventions (How It Works For Developers): Figure 1 - IronPDF: The C# PDF Library

When integrating IronPDF into your C# projects, it’s essential to maintain clean, readable code by following naming conventions. IronPDF allows you to generate PDFs from HTML content within your C# applications. While doing so, it’s important to follow naming conventions for your classes, methods, and variables to maintain consistency. Below is an example of a simple implementation of naming conventions to enhance code readability using IronPDF while adhering to these naming conventions:

using IronPdf;

public class PdfReportGenerator
{
    private readonly string _htmlContent;
    private readonly string _filePath;

    public PdfReportGenerator(string htmlContent, string filePath)
    {
        _htmlContent = htmlContent;
        _filePath = filePath;
    }

    public void GenerateReport()
    {
        var pdfRenderer = new ChromePdfRenderer();
        PdfDocument pdfDocument = pdfRenderer.RenderHtmlAsPdf(_htmlContent);
        pdfDocument.SaveAs(_filePath);
    }
}

public static class Program
{
    public static void Main()
    {
        var htmlContent = "<h1>Monthly Report</h1><p>Generated using IronPDF.</p>";
        var filePath = @"C:\Reports\MonthlyReport.pdf";
        PdfReportGenerator reportGenerator = new PdfReportGenerator(htmlContent, filePath);
        reportGenerator.GenerateReport();
    }
}
using IronPdf;

public class PdfReportGenerator
{
    private readonly string _htmlContent;
    private readonly string _filePath;

    public PdfReportGenerator(string htmlContent, string filePath)
    {
        _htmlContent = htmlContent;
        _filePath = filePath;
    }

    public void GenerateReport()
    {
        var pdfRenderer = new ChromePdfRenderer();
        PdfDocument pdfDocument = pdfRenderer.RenderHtmlAsPdf(_htmlContent);
        pdfDocument.SaveAs(_filePath);
    }
}

public static class Program
{
    public static void Main()
    {
        var htmlContent = "<h1>Monthly Report</h1><p>Generated using IronPDF.</p>";
        var filePath = @"C:\Reports\MonthlyReport.pdf";
        PdfReportGenerator reportGenerator = new PdfReportGenerator(htmlContent, filePath);
        reportGenerator.GenerateReport();
    }
}
$vbLabelText   $csharpLabel

By sticking to these naming conventions, your code stays professional, organized, and easy to read while using IronPDF for generating reports.

Conclusion

C# Naming Conventions (How It Works For Developers): Figure 2 - IronPDF licensing page

By following these C# naming conventions, you can ensure that your code is clean, readable, and easy to maintain. Whether it's using Pascal Case for class names, camel case for local variables, or using an underscore prefix for private fields, these conventions help establish a consistent codebase.

With IronPDF, you can jump in and explore all its capabilities with a free trial. This trial lets you experiment and see firsthand how well it integrates into your workflow. When you're ready to take the next step, licenses start at just $799.

자주 묻는 질문

C#의 클래스 및 인터페이스에 대한 일반적인 명명 규칙은 무엇인가요?

C#에서는 각 단어가 대문자로 시작하는 파스칼 대소문자를 사용하여 클래스 및 인터페이스의 이름을 지정해야 합니다. 또한 인터페이스에는 'ICustomer'와 같이 'I' 접두사가 포함되어야 합니다.

C#의 메서드 이름이 모범 사례를 준수하도록 하려면 어떻게 해야 하나요?

C#의 메서드 이름은 파스칼 대소문자 규칙을 따라야 하며 각 단어는 대문자로 시작해야 합니다. 이 규칙은 진입점 메서드인 Main를 포함한 모든 메서드에 적용됩니다.

C#에서 로컬 변수의 이름을 지정하는 권장 방법은 무엇인가요?

C#의 로컬 변수와 메서드 인수는 첫 단어는 소문자로, 그 이후의 각 단어는 대문자로 시작하는 대소문자를 사용하여 이름을 지정해야 합니다.

C#에서 정적 필드의 이름은 어떻게 지정해야 하나요?

C#의 정적 필드는 다른 필드와 구분하기 위해 밑줄 접두사를 사용하여 대소문자를 구분하여 이름을 지정해야 합니다.

C#에서 상수의 명명 규칙은 무엇인가요?

C#의 상수는 쉽게 구분할 수 있도록 모두 대문자로 명명하고 단어는 밑줄로 구분해야 합니다.

C# 명명 규칙을 준수하면서 라이브러리를 사용하려면 어떻게 해야 하나요?

IronPDF와 같은 C# 라이브러리를 사용할 때는 명명 규칙을 준수하여 깔끔하고 읽기 쉬운 코드를 유지하세요. 여기에는 클래스와 메서드에는 파스칼 케이스를, 변수에는 카멜 케이스를 사용하는 것이 포함됩니다. 예를 들어, 일관된 명명 규칙을 유지하면서 IronPDF를 사용하여 HTML에서 PDF를 생성할 수 있습니다.

C#에서 헝가리어 표기법을 권장하지 않는 이유는 무엇인가요?

헝가리 표기법은 코드 가독성을 떨어뜨릴 수 있으므로 최신 C# 개발에서는 사용하지 않는 것이 좋습니다. 대신 변수의 목적을 설명하는 의미 있는 이름을 사용하고 정해진 명명 규칙을 준수하세요.

이벤트 핸들러 메서드는 C#에서 어떻게 이름을 지정해야 하나요?

C#의 이벤트 핸들러 메서드는 처리하는 이벤트를 설명할 수 있도록 이름을 지정해야 하며, 일반적으로 이벤트 이름 뒤에 'On' 접두사를 사용해야 합니다. 이렇게 하면 메서드의 목적을 명확히 하는 데 도움이 됩니다.

C#의 비공개 필드에는 어떤 명명 규칙을 따라야 하나요?

C#의 비공개 필드는 언더스코어 접두사를 사용하여 대소문자를 구분하여 이름을 지정해야 합니다. 이렇게 하면 지역 변수 및 메서드 인자와 구별하는 데 도움이 됩니다.

명명 규칙이 C# 개발자에게 어떤 이점이 있나요?

명명 규칙은 코드 가독성과 유지 관리성을 향상시켜 개발자가 코드를 더 쉽게 이해하고 작업할 수 있게 해줍니다. IronPDF와 같은 라이브러리를 사용하는 프로젝트를 포함하여 C# 프로젝트의 일관된 명명 규칙은 전문적이고 깔끔한 코드베이스를 보장합니다.

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

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

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