Quick Commands & CLI
.NET CLI Essentials
# Create new project
dotnet new console -n MyApp
dotnet new webapi -n MyAPI
dotnet new mvc -n MyWeb
dotnet new classlib -n MyLib
# Run & Build
dotnet run
dotnet build
dotnet publish -c Release
dotnet watch run # Hot reload
# Package Management
dotnet add package PackageName
dotnet remove package PackageName
dotnet restore
dotnet list package
# Testing
dotnet test
dotnet test --logger trx
dotnet test --collect:"XPlat Code Coverage"
# EF Core
dotnet ef migrations add InitialCreate
dotnet ef database update
dotnet ef database drop
C# Language Quick Reference
Variable Declaration
// Implicit typing
var name = "John";
var age = 25;
var items = new List<string>();
// Explicit typing
string name = "John";
int age = 25;
List<string> items = new();
// Nullable types
string? nullableName = null;
int? nullableAge = null;
String Interpolation & Formatting
var name = "John";
var age = 25;
// String interpolation
$"Hello {name}, you are {age} years old"
$"Price: {price:C}" // Currency
$"Date: {date:yyyy-MM-dd}" // Date format
$"Percent: {value:P}" // Percentage
// String methods
"hello".ToUpper() // HELLO
"HELLO".ToLower() // hello
" text ".Trim() // text
"text".Contains("ex") // true
"text".StartsWith("te") // true
"text".EndsWith("xt") // true
Collections Quick Access
// List
var list = new List<string> { "a", "b", "c" };
list.Add("d");
list.Remove("a");
list.Count; // Length
// Dictionary
var dict = new Dictionary<string, int>
{
["key1"] = 1,
["key2"] = 2
};
dict.ContainsKey("key1");
dict.TryGetValue("key1", out int value);
// Array
var array = new string[] { "a", "b", "c" };
var array2 = new string[5]; // Fixed size
LINQ One-Liners
var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Filtering & Selection
numbers.Where(x => x > 5) // Filter
numbers.Select(x => x * 2) // Transform
numbers.First(x => x > 5) // First match
numbers.FirstOrDefault(x => x > 100) // First or null
numbers.Any(x => x > 5) // Boolean check
numbers.All(x => x > 0) // All match
numbers.Count(x => x > 5) // Count matches
// Aggregation
numbers.Sum() // Sum all
numbers.Average() // Average
numbers.Max() // Maximum
numbers.Min() // Minimum
// Grouping & Ordering
numbers.OrderBy(x => x) // Ascending
numbers.OrderByDescending(x => x) // Descending
numbers.GroupBy(x => x % 2) // Group by remainder
numbers.Distinct() // Remove duplicates
numbers.Take(5) // First 5
numbers.Skip(3) // Skip first 3
ASP.NET Core Quick Setup
Minimal API (Program.cs)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
// Quick endpoints
app.MapGet("/", () => "Hello World!");
app.MapGet("/users/{id}", (int id) => $"User {id}");
app.MapPost("/users", (User user) => Results.Created($"/users/{user.Id}", user));
app.Run();
Controller Template
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<User>> Get() => Ok(users);
[HttpGet("{id}")]
public ActionResult<User> Get(int id) =>
users.FirstOrDefault(u => u.Id == id) is User user
? Ok(user)
: NotFound();
[HttpPost]
public ActionResult<User> Post([FromBody] User user)
{
users.Add(user);
return CreatedAtAction(nameof(Get), new { id = user.Id }, user);
}
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] User user) =>
users.Any(u => u.Id == id) ? Ok() : NotFound();
[HttpDelete("{id}")]
public IActionResult Delete(int id) =>
users.RemoveAll(u => u.Id == id) > 0 ? Ok() : NotFound();
}
Entity Framework Core Shortcuts
DbContext Quick Setup
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<User> Users { get; set; }
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasKey(u => u.Id);
modelBuilder.Entity<User>()
.Property(u => u.Name)
.IsRequired()
.HasMaxLength(100);
}
}