Zum Fußzeileninhalt springen
.NET HILFE

C# Namenskonventionen (Wie es für Entwickler funktioniert)

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();
}
Public Class Customer
	Public Property Balance() As Decimal
End Class

Public Interface ICustomer
	Function GetBalance() As Decimal
End Interface
$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;
}
Public Function CalculateInterest(ByVal principal As Decimal, ByVal rate As Decimal) As Decimal
	Return principal * rate
End Function
$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; }
Public Property DateOpened() As DateTime
Public Property Reserves() As Decimal
$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);
}
Public Sub SelectCustomer(ByVal customerName As String)
	Dim selectedCustomer = FindCustomer(customerName)
End Sub
$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
}
Public Sub AddCustomer(ByVal customerName As String, ByVal dateOpened As DateTime)
	' Add customer logic
End Sub
$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;
Private Shared _totalCustomers As Integer
$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;
Public Const MAX_CUSTOMERS As Integer = 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
}
Private Sub OnCustomerAdded(ByVal sender As Object, ByVal e As EventArgs)
	' Event handling logic
End Sub
$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;
Private _customerName As String
$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
};
Dim seattleCustomer = New Customer With {
	.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
    }
}
Public Sub ProcessTransaction()
	Try
		' Transaction logic
	Catch ex As InvalidOperationException
		' Handle exception
	End Try
End Sub
$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;
}
Public Function CalculateTotalBalance() As Decimal
	Return _totalCustomers * balancePerCustomer
End Function
$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;
Public Const PI As Double = 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;
    }
}
Public Sub AddCustomer(ByVal customerName As String)
	If Not String.IsNullOrEmpty(customerName) Then
		_customerName = customerName
	End If
End Sub
$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; }
Public Property CustomerName() As String
Public Property OrderCount() As Integer
$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();
    }
}
Imports IronPdf

Public Class PdfReportGenerator
	Private ReadOnly _htmlContent As String
	Private ReadOnly _filePath As String

	Public Sub New(ByVal htmlContent As String, ByVal filePath As String)
		_htmlContent = htmlContent
		_filePath = filePath
	End Sub

	Public Sub GenerateReport()
		Dim pdfRenderer = New ChromePdfRenderer()
		Dim pdfDocument As PdfDocument = pdfRenderer.RenderHtmlAsPdf(_htmlContent)
		pdfDocument.SaveAs(_filePath)
	End Sub
End Class

Public Module Program
	Public Sub Main()
		Dim htmlContent = "<h1>Monthly Report</h1><p>Generated using IronPDF.</p>"
		Dim filePath = "C:\Reports\MonthlyReport.pdf"
		Dim reportGenerator As New PdfReportGenerator(htmlContent, filePath)
		reportGenerator.GenerateReport()
	End Sub
End Module
$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.

Häufig gestellte Fragen

Was sind die allgemeinen Namenskonventionen für Klassen und Schnittstellen in C#?

In C# sollten Klassen und Schnittstellen in Pascal Case benannt werden, wobei jedes Wort mit einem Großbuchstaben beginnt. Schnittstellen sollten ebenfalls ein 'I'-Präfix enthalten, wie zum Beispiel 'ICustomer'.

Wie kann ich sicherstellen, dass Methodennamen in C# den bewährten Praktiken entsprechen?

Methodennamen in C# sollten der Pascal Case-Konvention folgen, wobei jedes Wort mit einem Großbuchstaben beginnt. Diese Konvention gilt für alle Methoden, einschließlich der Einstiegspunktmethode Main.

Wie sollte man lokale Variablen in C# benennen?

Lokale Variablen und Methodenargumente in C# sollten in Camel Case benannt werden, was bedeutet, dass das erste Wort klein geschrieben wird und jedes folgende Wort mit einem Großbuchstaben beginnt.

Wie sollten statische Felder in C# benannt werden?

Statische Felder in C# sollten in Camel Case mit einem Unterstrich-Präfix benannt werden, um sie von anderen Feldern zu unterscheiden.

Was ist die Namenskonvention für Konstanten in C#?

Konstanten in C# sollten unter Verwendung von Großbuchstaben benannt werden, wobei die Wörter durch Unterstriche getrennt sind, um sie leicht erkennbar zu machen.

Wie kann ich eine Bibliothek nutzen und gleichzeitig C#-Namenskonventionen einhalten?

Bei der Verwendung von Bibliotheken in C#, wie IronPDF, sollten Sie durch die Befolgung der Namenskonventionen sauberen, lesbaren Code beibehalten. Dazu gehört die Verwendung von Pascal Case für Klassen und Methoden sowie Camel Case für Variablen. Sie können beispielsweise PDFs von HTML mit IronPDF generieren und dabei konsistente Namenspraktiken einhalten.

Warum wird die ungarische Notation in C# nicht empfohlen?

Die ungarische Notation wird in der modernen C#-Entwicklung nicht empfohlen, da sie den Code weniger lesbar machen kann. Verwenden Sie stattdessen sinnvolle Namen, die den Zweck der Variablen beschreiben und sich an etablierte Namenskonventionen halten.

Wie sollten Ereignis-Handler-Methoden in C# benannt werden?

Ereignis-Handler-Methoden in C# sollten so benannt werden, dass sie das bearbeitete Ereignis beschreiben, typischerweise mit dem Präfix 'On', gefolgt vom Ereignisnamen. Dies hilft, den Zweck der Methode zu verdeutlichen.

Welche Namenskonventionen sollten für private Felder in C# befolgt werden?

Private Felder in C# sollten in Camel Case mit einem Unterstrich-Präfix benannt werden. Dies hilft, sie von lokalen Variablen und Methodenargumenten zu unterscheiden.

Welchen Nutzen bringen Namenskonventionen für C#-Entwickler?

Namenskonventionen verbessern die Lesbarkeit und Wartbarkeit des Codes, was es Entwicklern erleichtert, den Code zu verstehen und damit zu arbeiten. Konsistente Benennung in C#-Projekten, einschließlich derer, die Bibliotheken wie IronPDF verwenden, sorgt für eine professionelle und saubere Codebasis.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen