C# Clean code
- User
C# Clean code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
C# Clean code
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Writing clean code in C# is essential for building maintainable, scalable, and collaborative applications. Below is a structured guide to help you achieve clean, readable, and efficient C# code, aligned with best practices and principles.
// Bad
int x = 10;
// Good
int userAge = 10;
// Bad
string[] GetData();
// Good
string[] GetActiveUsernames();
UI, HTTP).PascalCase for classes, methods, and public members.camelCase for local variables and parameters.// Bad
void ProcessOrder(Order order) {
ValidateOrder(order);
CalculateDiscount(order);
SaveToDatabase(order);
SendEmail(order);
}
// Good
void ProcessOrder(Order order) =>
ValidateOrder(order)
&& ApplyDiscount(order)
&& SaveOrder(order)
&& NotifyUser(order);
async/await for asynchronous operations:
public async Task<User> FetchUserAsync(int id) {
return await _context.Users.FindAsync(id);
}
// Good: Use properties
public class Person {
public string Name { get; private set; }
public void UpdateName(string newName) {
if (string.IsNullOrEmpty(newName)) throw new ArgumentException();
Name = newName;
}
}
// Prefer
public class OrderProcessor {
private readonly IOrderValidator _validator;
public OrderProcessor(IOrderValidator validator) => _validator = validator;
}
// Over deep inheritance trees
public class SpecialOrder : Order { ... }
// Good: Explain reasoning
// Use a timeout to prevent infinite loops in unreliable APIs
var result = await api.CallAsync().Timeout(5000);
// Bad: Stating the obvious
// Increment i by 1
i++;
/// <summary>
/// Calculates the total price after applying discounts.
/// </summary>
public decimal CalculateTotal(Order order) { ... }
// Good
if (string.IsNullOrEmpty(input)) throw new ArgumentException("Input is required.");
// Bad: Avoid empty catch blocks
try { ... }
catch (Exception) { } // Swallowing exceptions
public void AddUser(User user) {
if (user == null) throw new ArgumentNullException(nameof(user));
// Proceed
}
public void Configure() {
var settings = LoadSettings();
if (settings.IsValid) {
Initialize();
}
}
var when the type is obvious:
var user = new User(); // Clear from context
PascalCase for methods).Example (Dependency Inversion):
// Good
public class OrderProcessor {
private readonly IPaymentGateway _gateway;
public OrderProcessor(IPaymentGateway gateway) => _gateway = gateway;
}
// Bad
public class OrderProcessor {
private readonly PayPalGateway _gateway; // Concrete dependency
}
public record User(string Name, int Age);
if (value is string s) { Console.WriteLine(s); }
var activeUsers = users.Where(u => u.IsActive).ToList();
[Fact]
public void CalculateTotal_WithDiscount_ReturnsCorrectAmount() { ... }
[Fact]
public void Add_TwoNumbers_ReturnsSum() {
// Arrange
var calc = new Calculator();
// Act
var result = calc.Add(2, 3);
// Assert
Assert.Equal(5, result);
}
// Bad
if (user.Role == 1) { ... }
// Good
public enum Role { Admin = 1, User = 2 }
if (user.Role == Role.Admin) { ... }
Before:
public class Calculator {
public int Calculate(string op, int a, int b) {
if (op == "add") return a + b;
if (op == "sub") return a - b;
return 0;
}
}
After:
public interface IOperation {
int Execute(int a, int b);
}
public class AddOperation : IOperation {
public int Execute(int a, int b) => a + b;
}
public class Calculator {
private readonly IOperation _operation;
public Calculator(IOperation operation) => _operation = operation;
public int Calculate(int a, int b) => _operation.Execute(a, b);
}
record, required, primary constructors).By following these principles and practices, you'll write C# code that is easier to maintain, test, and scale. 🚀