.NET Cheatsheet

What is .NET .NET Versions Installation CLI Basics Project Types C# Basics OOP Async/Await LINQ Collections Exceptions Delegates Events Generics Reflection Attributes DI Configuration Logging Web API MVC EF Core Testing Deployment Performance Security Best Practices

What is .NET?

Intro

.NET is a free, cross-platform, open-source developer platform for building many types of applications. It provides a unified framework for building web, mobile, desktop, IoT, and cloud applications.

.NET Versions

Versions
VersionReleaseSupport
.NET 82023LTS
.NET 62021LTS
.NET 52020EOL

Installation

Setup
# Check installed version
dotnet --version

# List installed SDKs
dotnet --list-sdks

# List installed runtimes
dotnet --list-runtimes

CLI Basics

CLI
# Create new project
dotnet new console -n MyApp

# Build project
dotnet build

# Run project
dotnet run

# Add package
dotnet add package Newtonsoft.Json

Project Types

Projects
# Create different project types
dotnet new console
dotnet new web
dotnet new webapi
dotnet new mvc
dotnet new classlib
dotnet new xunit

C# Basics

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, .NET!");
            
            var name = "World";
            var message = $"Hello, {name}!";
            
            int number = 42;
            string text = number.ToString();
        }
    }
}

Object-Oriented Programming

OOP
public class Animal
{
    protected string Name { get; set; }
    
    public virtual void MakeSound()
    {
        Console.WriteLine("Some sound");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof!");
    }
}

Async/Await

Async
public async Task GetDataAsync()
{
    await Task.Delay(1000); // Simulate async work
    return "Data loaded";
}

public async Task Main()
{
    var data = await GetDataAsync();
    Console.WriteLine(data);
}

LINQ (Language Integrated Query)

LINQ
var numbers = new List { 1, 2, 3, 4, 5 };

// Method syntax
var evenNumbers = numbers.Where(n => n % 2 == 0);

// Query syntax
var result = from n in numbers
             where n % 2 == 0
             select n;

// Aggregation
var sum = numbers.Sum();
var max = numbers.Max();

Collections

Collections
// List
var list = new List { 1, 2, 3 };
list.Add(4);

// Dictionary
var dict = new Dictionary();
dict["key"] = 42;

// HashSet
var set = new HashSet { 1, 2, 3 };
set.Add(4);

// Queue
var queue = new Queue();
queue.Enqueue("first");

Exception Handling

Exceptions
try
{
    var result = int.Parse("invalid");
}
catch (FormatException ex)
{
    Console.WriteLine($"Format error: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"General error: {ex.Message}");
}
finally
{
    // Always executed
    Console.WriteLine("Cleanup");
}

Delegates

Delegates
// Delegate declaration
public delegate int MathOperation(int x, int y);

// Using delegates
MathOperation add = (x, y) => x + y;
MathOperation multiply = (x, y) => x * y;

int result1 = add(5, 3);      // 8
int result2 = multiply(5, 3); // 15

// Action and Func (built-in delegates)
Action print = Console.WriteLine;
Func square = x => x * x;

Events

Events
public class Button
{
    public event EventHandler Clicked;
    
    public void Click()
    {
        Clicked?.Invoke(this, EventArgs.Empty);
    }
}

// Usage
var button = new Button();
button.Clicked += (sender, e) => Console.WriteLine("Button clicked!");
button.Click();

Generics

Generics
public class Repository
{
    private List _items = new List();
    
    public void Add(T item)
    {
        _items.Add(item);
    }
    
    public T Get(int index)
    {
        return _items[index];
    }
}

// Usage
var stringRepo = new Repository();
var intRepo = new Repository();

Reflection

Reflection
using System.Reflection;

var type = typeof(string);
var methods = type.GetMethods();

// Get property value
var obj = new { Name = "John", Age = 30 };
var property = obj.GetType().GetProperty("Name");
var value = property.GetValue(obj);

// Create instance dynamically
var instance = Activator.CreateInstance(typeof(string));

Attributes

Attributes
[Serializable]
public class Person
{
    [Required]
    [StringLength(50)]
    public string Name { get; set; }
    
    [Range(0, 120)]
    public int Age { get; set; }
}

// Custom attribute
[AttributeUsage(AttributeTargets.Class)]
public class MyAttribute : Attribute
{
    public string Description { get; set; }
}

Dependency Injection

DI
// Service interface
public interface IEmailService
{
    void SendEmail(string to, string subject);
}

// Service implementation
public class EmailService : IEmailService
{
    public void SendEmail(string to, string subject) { }
}

// Constructor injection
public class UserService
{
    private readonly IEmailService _emailService;
    
    public UserService(IEmailService emailService)
    {
        _emailService = emailService;
    }
}

// Registration
services.AddScoped();

Configuration

Config
// appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=...;Database=...;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
}

// Reading configuration
public class AppSettings
{
    public string ConnectionString { get; set; }
    public LoggingSettings Logging { get; set; }
}

// In Startup.cs
services.Configure(Configuration);

Logging

Logging
// In Startup.cs
services.AddLogging(builder =>
{
    builder.AddConsole();
    builder.AddDebug();
    builder.AddFile("logs/app-{Date}.txt");
});

// In controller/service
public class UserController : ControllerBase
{
    private readonly ILogger _logger;
    
    public UserController(ILogger logger)
    {
        _logger = logger;
    }
    
    public IActionResult Get(int id)
    {
        _logger.LogInformation("Getting user with ID: {UserId}", id);
        return Ok();
    }
}

Web API

API
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    [HttpGet]
    public async Task>> GetUsers()
    {
        return Ok(await _userService.GetAllAsync());
    }
    
    [HttpGet("{id}")]
    public async Task> GetUser(int id)
    {
        var user = await _userService.GetByIdAsync(id);
        if (user == null)
            return NotFound();
        return Ok(user);
    }
    
    [HttpPost]
    public async Task> CreateUser(User user)
    {
        var created = await _userService.CreateAsync(user);
        return CreatedAtAction(nameof(GetUser), new { id = created.Id }, created);
    }
}

MVC Pattern

MVC
// Model
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

// Controller
public class HomeController : Controller
{
    public IActionResult Index()
    {
        var users = _userService.GetAll();
        return View(users);
    }
    
    [HttpPost]
    public IActionResult Create(User user)
    {
        if (ModelState.IsValid)
        {
            _userService.Create(user);
            return RedirectToAction("Index");
        }
        return View(user);
    }
}

// View (Razor)
@model IEnumerable
@foreach (var user in Model)
{
    
@user.Name - @user.Email
}

Entity Framework Core

EF Core
// DbContext
public class AppDbContext : DbContext
{
    public DbSet Users { get; set; }
    
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer(Configuration.GetConnectionString("Default"));
    }
}

// Entity
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

// Usage
public class UserService
{
    private readonly AppDbContext _context;
    
    public async Task GetByIdAsync(int id)
    {
        return await _context.Users.FindAsync(id);
    }
    
    public async Task CreateAsync(User user)
    {
        _context.Users.Add(user);
        await _context.SaveChangesAsync();
    }
}

Testing

Testing
// Unit test
public class UserServiceTests
{
    [Fact]
    public async Task GetById_ValidId_ReturnsUser()
    {
        // Arrange
        var mockRepo = new Mock();
        var expectedUser = new User { Id = 1, Name = "John" };
        mockRepo.Setup(r => r.GetByIdAsync(1))
                .ReturnsAsync(expectedUser);
        
        var service = new UserService(mockRepo.Object);
        
        // Act
        var result = await service.GetByIdAsync(1);
        
        // Assert
        Assert.Equal(expectedUser, result);
    }
}

// Integration test
public class UserControllerTests : IClassFixture>
{
    private readonly WebApplicationFactory _factory;
    
    [Fact]
    public async Task Get_ReturnsSuccessStatusCode()
    {
        var client = _factory.CreateClient();
        var response = await client.GetAsync("/api/users");
        response.EnsureSuccessStatusCode();
    }
}

Deployment

Deploy
# Publish for production
dotnet publish -c Release -o ./publish

# Self-contained (includes runtime)
dotnet publish -c Release -r win-x64 --self-contained true

# Framework-dependent
dotnet publish -c Release -r win-x64 --self-contained false

# Docker
FROM mcr.microsoft.com/dotnet/aspnet:8.0
COPY bin/Release/net8.0/publish/ App/
WORKDIR /App
ENTRYPOINT ["dotnet", "MyApp.dll"]

Performance

Performance
// Memory pooling
using var pool = ArrayPool.Shared;
var buffer = pool.Rent(1024);
try
{
    // Use buffer
}
finally
{
    pool.Return(buffer);
}

// Caching
services.AddMemoryCache();
services.AddDistributedRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

// In service
public class CacheService
{
    private readonly IMemoryCache _cache;
    
    public async Task GetOrSetAsync(string key, Func> factory)
    {
        if (_cache.TryGetValue(key, out T value))
            return value;
            
        value = await factory();
        _cache.Set(key, value, TimeSpan.FromMinutes(10));
        return value;
    }
}

Security

Security
// Authentication
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true
        };
    });

// Authorization
[Authorize(Roles = "Admin")]
public class AdminController : ControllerBase
{
    [AllowAnonymous]
    public IActionResult PublicAction() { }
}

// Input validation
public class UserModel
{
    [Required]
    [StringLength(50)]
    public string Name { get; set; }
    
    [EmailAddress]
    public string Email { get; set; }
}

Best Practices

Best Practices
// SOLID Principles
// Single Responsibility
public class UserService
{
    public async Task GetUserAsync(int id) { }
    public async Task CreateUserAsync(User user) { }
}

// Dependency Inversion
public interface IUserRepository
{
    Task GetByIdAsync(int id);
}

public class UserService
{
    private readonly IUserRepository _repository;
    
    public UserService(IUserRepository repository)
    {
        _repository = repository;
    }
}

// Error handling
public async Task> GetUserAsync(int id)
{
    try
    {
        var user = await _repository.GetByIdAsync(id);
        return user != null ? Result.Success(user) : Result.NotFound();
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Error getting user {UserId}", id);
        return Result.Error("Failed to get user");
    }
}