C#: Modern Development with .NET
Master C# and the .NET ecosystem for enterprise applications and games
1 Loading...
C#: Modern Development with .NET
C# is a modern, object-oriented, type-safe programming language developed by Microsoft. Since its release in 2000, C# has evolved into a powerful and versatile language used in web development, desktop, mobile, games (Unity), and cloud computing.
Why C#? C# combines the productivity of high-level languages with near-system-level performance. With .NET Core/5+, it’s now truly cross-platform.
Modern Features
- LINQ - Language Integrated Queries
- Async/Await - Elegant asynchronous programming
- Pattern Matching - Expressive pattern matching
- Records - Concise immutable types
- Nullable Reference Types - Null safety
- Source Generators - Compile-time code generation
Fundamentals
Types and Variables
// Primitive types
string name = "Maria";
int age = 25;
double height = 1.68;
bool active = true;
char initial = 'M';
decimal salary = 5000.50m;
// Type inference with var
var email = "[email protected]";
var list = new List<int> { 1, 2, 3 };
// Nullable types
int? optionalValue = null;
optionalValue = 42;
// Arrays
int[] numbers = { 1, 2, 3, 4, 5 };
string[,] matrix = { { "a", "b" }, { "c", "d" } };
// Collections
var fruits = new List<string> { "apple", "banana", "orange" };
var users = new Dictionary<string, int>
{
["alice"] = 25,
["bob"] = 30
};
// Tuples
(string Name, int Age) person = ("Maria", 25);
var (name2, age2) = person; // Deconstruction
Classes and Objects
// Traditional class
public class User
{
// Auto-properties
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; private set; }
public DateTime CreatedAt { get; init; } // Init-only
// Constructor
public User(int id, string name, string email)
{
Id = id;
Name = name;
Email = email;
CreatedAt = DateTime.UtcNow;
}
// Method
public string Greet() => $"Hello, {Name}!";
// Expression-bodied property
public bool IsActive => CreatedAt > DateTime.UtcNow.AddDays(-30);
}
// Record (C# 9+) - immutable by default
public record Product(string Name, decimal Price, int Quantity)
{
public decimal TotalValue => Price * Quantity;
}
// Abstract class
public abstract class Shape
{
public abstract double CalculateArea();
public abstract double CalculatePerimeter();
public void Describe()
{
Console.WriteLine($"Area: {CalculateArea():F2}, Perimeter: {CalculatePerimeter():F2}");
}
}
public class Rectangle : Shape
{
public double Width { get; }
public double Height { get; }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
public override double CalculateArea() => Width * Height;
public override double CalculatePerimeter() => 2 * (Width + Height);
}
Interfaces and Generics
// Interface
public interface IRepository<T> where T : class
{
Task<T?> GetByIdAsync(int id);
Task<IEnumerable<T>> GetAllAsync();
Task AddAsync(T entity);
Task UpdateAsync(T entity);
Task DeleteAsync(int id);
}
// Implementation
public class UserRepository : IRepository<User>
{
private readonly List<User> _users = new();
public Task<User?> GetByIdAsync(int id)
{
return Task.FromResult(_users.FirstOrDefault(u => u.Id == id));
}
public Task<IEnumerable<User>> GetAllAsync()
{
return Task.FromResult<IEnumerable<User>>(_users);
}
public Task AddAsync(User entity)
{
_users.Add(entity);
return Task.CompletedTask;
}
public Task UpdateAsync(User entity)
{
var index = _users.FindIndex(u => u.Id == entity.Id);
if (index >= 0) _users[index] = entity;
return Task.CompletedTask;
}
public Task DeleteAsync(int id)
{
_users.RemoveAll(u => u.Id == id);
return Task.CompletedTask;
}
}
LINQ
var products = new List<Product>
{
new("Laptop", 3500, 2),
new("Mouse", 150, 10),
new("Keyboard", 300, 5),
new("Monitor", 1200, 3)
};
// Query syntax
var expensive = from p in products
where p.Price > 500
orderby p.Price descending
select p;
// Method syntax
var cheap = products
.Where(p => p.Price <= 500)
.OrderBy(p => p.Name)
.ToList();
// Aggregations
var total = products.Sum(p => p.TotalValue);
var average = products.Average(p => p.Price);
var cheapest = products.MinBy(p => p.Price);
// Grouping
var byPriceRange = products
.GroupBy(p => p.Price switch
{
< 200 => "Cheap",
< 1000 => "Medium",
_ => "Expensive"
})
.ToDictionary(g => g.Key, g => g.ToList());
Async/Await
public class HttpService
{
private readonly HttpClient _client = new();
// Async method
public async Task<string> FetchDataAsync(string url)
{
try
{
var response = await _client.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Error: {ex.Message}");
throw;
}
}
// Multiple tasks in parallel
public async Task<IEnumerable<string>> FetchManyAsync(IEnumerable<string> urls)
{
var tasks = urls.Select(url => FetchDataAsync(url));
return await Task.WhenAll(tasks);
}
}
Pattern Matching
// Switch expression
public static string DescribeObject(object obj) => obj switch
{
null => "Null",
string s => $"String: {s}",
int n when n > 0 => $"Positive integer: {n}",
int n => $"Integer: {n}",
{ } x => $"Object: {x.GetType().Name}"
};
// Property patterns
public record Order(string Status, decimal Total, bool Priority);
public static decimal CalculateDiscount(Order order) => order switch
{
{ Status: "VIP", Total: > 1000 } => order.Total * 0.20m,
{ Priority: true, Total: > 500 } => order.Total * 0.15m,
{ Total: > 1000 } => order.Total * 0.10m,
_ => 0
};
Learning Checklist
- Master types, classes, and interfaces
- Learn LINQ and lambda expressions
- Study async/await and Task
- Explore pattern matching
- Practice with ASP.NET Core
- Understand dependency injection
- Build a complete REST API
Essential Resources
Quote
“C# was designed to be a simple, modern, general-purpose, object-oriented language.” - Anders Hejlsberg
C# is an excellent choice for enterprise development, Unity games, and cloud-native applications!