C# best practices — write clean, maintainable code.
1. Naming conventions:
1// PascalCase for public members2public string UserName { get; set; }34// _camelCase for private fields5private readonly ILogger _logger;67// camelCase for parameters and locals8void Process(string input, int count) { }
2. Use async/await properly:
1// Always await async methods2await GetDataAsync();34// Don't use .Result or .Wait()
3. Use LINQ wisely:
1// Good — fluent, readable2var result = list3 .Where(x => x > 5)4 .OrderBy(x => x)5 .Select(x => x * 2);
4. Handle exceptions properly:
1// Catch specific exceptions2catch (HttpRequestException ex) { }34// Don't catch Exception unless necessary
5. Use dependency injection:
1// Good — inject dependencies2public class Service(IRepository repo) { }34// Bad — new inside class5public class Service { var repo = new Repository(); }
6. Write tests:
1[Fact]2public void ShouldCalculateTotal()3{4 var service = new OrderService();5 var total = service.CalculateTotal();6 Assert.Equal(100, total);7}