Writing maintainable, performant, and idiomatic C# code.
BankAccount, GetBalance()firstName, itemCount_balance, _loggerILogger, IRepository<T>GetDataAsync(), SaveAsync()// Records for immutable data
public record UserDto(int Id, string Name, string Email);
// Primary constructors (C# 12)
public class Service(ILogger logger, IRepository repo)
{
public async Task DoWorkAsync() => logger.LogInformation("Working...");
}
// Collection expressions (C# 12)
int[] numbers = [1, 2, 3, 4, 5];
List<string> names = ["Alice", "Bob"];
public class ResourceManager : IDisposable
{
private bool _disposed = false;
private StreamReader _reader;
public ResourceManager(string path) => _reader = new StreamReader(path);
public void Dispose()
{
if (!_disposed)
{
_reader.Dispose();
_disposed = true;
}
}
}
using var rm = new ResourceManager("data.txt"); // auto-disposed