Untitled
unknown
csharp
a year ago
4.8 kB
18
Indexable
#can you show me all the c# naming conventions and coding standards
#Here's a comprehensive guide to C# naming conventions and coding standards. Following these guidelines helps improve code readability, maintainability, and consistency.
1. General Naming Conventions
PascalCase: Capitalize the first letter of each word. Used for classes, methods, properties, namespaces, etc.
camelCase: Capitalize the first letter of each word except the first one. Used for private fields, parameters, and local variables.
UPPER_CASE: Use all uppercase letters with underscores separating words. Typically used for constants.
2. Naming Conventions for Different Elements
Classes and Structs
Convention: PascalCase
Example: Customer, InvoiceProcessor
Guideline: Use nouns or noun phrases. Avoid prefixes like C, T, etc.
Interfaces
Convention: PascalCase starting with an "I"
Example: IRepository, ILogger
Guideline: Name interfaces to indicate capabilities, like IReadable.
Methods
Convention: PascalCase
Example: CalculateTotal(), GetCustomer()
Guideline: Use verbs or verb phrases that describe the action.
Properties
Convention: PascalCase
Example: FirstName, TotalAmount
Guideline: Use nouns or noun phrases.
Fields
Convention: camelCase, optionally with an underscore prefix (_)
Example: _total, orderCount
Guideline: Use private fields for internal state and properties for exposing state.
Constants
Convention: UPPER_CASE with underscores
Example: MAX_VALUE, DEFAULT_TIMEOUT
Guideline: Use for immutable values that are constant in nature.
Enums
Convention: PascalCase for names, and UPPER_CASE for values
Example:
csharp
Copiar código
enum OrderStatus { Pending, Completed, Cancelled }
Guideline: Avoid using Enum suffix.
Namespaces
Convention: PascalCase
Example: MyCompany.Project.Module
Guideline: Use hierarchical naming with the company's name, project, and module.
Parameters
Convention: camelCase
Example: int orderId, string customerName
Guideline: Use descriptive names that indicate purpose.
Local Variables
Convention: camelCase
Example: int count, string result
Guideline: Use short but descriptive names. Avoid single letters except in loop counters.
Delegates
Convention: PascalCase with EventHandler or Callback suffix
Example: OrderCompletedHandler, DataProcessedCallback
Guideline: Name should indicate the operation being delegated.
3. Coding Standards
Braces
Always use braces {} even for single-line statements to improve readability and maintainability.
csharp
Copiar código
// Good
if (condition)
{
DoSomething();
}
// Bad
if (condition)
DoSomething();
Indentation and Spacing
Use 4 spaces per indentation level. Do not use tabs.
Leave a space after keywords (if, for, while, etc.) and before the opening brace.
csharp
Copiar código
if (condition) // Good
{
// ...
}
Line Length
Keep line length to a maximum of 80-100 characters to improve readability.
Comments
Use XML comments (///) for public members.
Write inline comments sparingly and only if they add value.
csharp
Copiar código
/// <summary>
/// Calculates the total amount of the order.
/// </summary>
/// <returns>Total amount as a decimal.</returns>
Error Handling
Use try-catch blocks to handle exceptions gracefully. Avoid swallowing exceptions without logging.
csharp
Copiar código
try
{
// code that might throw
}
catch (Exception ex)
{
// handle exception
Logger.Log(ex);
}
LINQ and Collections
Use LINQ for querying collections. Avoid complex, nested loops when LINQ can simplify the code.
csharp
Copiar código
// Good
var highScores = scores.Where(score => score > 90).ToList();
// Bad
var highScores = new List<int>();
foreach (var score in scores)
{
if (score > 90)
highScores.Add(score);
}
Use of var Keyword
Use var when the type is obvious from the right side of the assignment; otherwise, explicitly specify the type.
csharp
Copiar código
var customer = new Customer(); // Good
int count = GetCount(); // Good
Method Length
Keep methods short and focused on a single task. Ideally, methods should not exceed 20-30 lines.
4. Best Practices
Single Responsibility Principle (SRP)
Each class and method should have one responsibility or functionality.
Consistent Naming
Ensure consistent naming throughout the project to avoid confusion.
Avoid Magic Numbers
Replace magic numbers with named constants to improve code readability.
Proper Error Messages
Provide meaningful error messages in exceptions.
Avoid Hardcoding Strings
Use constants, resources, or configuration files for strings that are reused or displayed to the user.
Following these guidelines helps create clean, maintainable, and professional-looking C# code! If you need any more details or examples on specific sections, let me know!Editor is loading...
Leave a Comment