Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Câu hỏi Phân biệt

.NET Core vs .NET Framework

Aspect.NET Core.NET Framework
PlatformCross-platform (Windows, Linux, macOS)Windows only
SourceOpen sourceMostly closed source
PerformanceBetter, optimized runtimeLegacy
ModularityPackage-based (NuGet)Full framework
CLIFull CLI supportLimited
Side-by-sideMultiple versionsSingle version per machine
Use caseModern apps, microservicesLegacy Windows apps

MVC vs Web API vs Minimal API

MVC

  • Hỗ trợ Views (Razor pages)
  • Phù hợp cho web applications với UI
  • Convention-based routing
  • Model binding đầy đủ
  • ViewBag, ViewData
public class HomeController : Controller
{
    public IActionResult Index()
    {
        ViewData["Title"] = "Home";
        return View();
    }
}

Web API

  • RESTful services, JSON/XML
  • Không có Views
  • Attribute routing
  • Content negotiation
  • [ApiController] attribute
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Ok();
}

Minimal APIs

  • Rút gọn code
  • Không cần Controller
  • Top-level statements
  • Phù hợp cho microservices
  • Lambda expressions
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/products", () => Results.Ok(new { name = "Product" }));

app.Run();

So sánh

FeatureMVCWeb APIMinimal API
Views✅ Yes❌ No❌ No
Controllers✅ Yes✅ Yes❌ No
RoutingConvention + AttributeAttributeMapGet/MapPost
Model BindingFullFullLimited
TestabilityMediumMediumHigh
Use caseWeb appsAPIsMicroservices

Abstract class vs Interface

Abstract Class

public abstract class Animal
{
    public string Name { get; set; }
    
    // Abstract method - phải implement
    public abstract void MakeSound();
    
    // Virtual method - có thể override
    public virtual void Sleep()
    {
        Console.WriteLine("Sleeping...");
    }
    
    // Non-abstract method
    public void Eat()
    {
        Console.WriteLine("Eating...");
    }
}

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

Interface

public interface IAnimal
{
    string Name { get; set; }
    void MakeSound();
}

public interface IFlyable
{
    void Fly();
}

public interface IPlayable
{
    void Play();
}

So sánh

AspectAbstract ClassInterface
Multiple inheritance❌ No✅ Yes
Constructor✅ Yes❌ No
Fields✅ Yes❌ No (properties only)
Access modifiers✅ Yes❌ No (public implicit)
Default implementation✅ Yes✅ Yes (C# 8+)
State✅ Can have❌ No
InheritanceSingleMultiple
Use case“is-a” relationship“can-do” capability

IEnumerable vs IQueryable

IEnumerable

public IEnumerable<Product> GetProducts()
{
    return _context.Products; // Local collection
}

foreach (var product in GetProducts())
{
    // Process
}
  • Thực thi trên client
  • Toàn bộ data được load vào memory trước khi filter
  • Phù hợp cho small datasets hoặc in-memory data

IQueryable

public IQueryable<Product> GetProducts()
{
    return _context.Products; // Query provider
}

var results = GetProducts()
    .Where(p => p.Price > 100)
    .OrderBy(p => p.Name);
    
// Query được translate sang SQL và execute trên database
  • Thực thi trên database
  • Query được build và translate sang SQL
  • Phù hợp cho large datasets và remote data sources

So sánh

AspectIEnumerableIQueryable
LocationClient-sideServer-side
ExecutionIn-memoryDatabase query
SQL Translation❌ No✅ Yes
DeferredYesYes
Use caseIn-memory collectionsDatabase queries
PerformanceSlow with large dataOptimized

Khi nào dùng?

// ✅ IEnumerable - Khi đã có data trong memory
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var evens = numbers.Where(n => n % 2 == 0);

// ✅ IQueryable - Khi query database
var products = _context.Products
    .Where(p => p.Price > 100)
    .OrderBy(p => p.Name);

// ❌ Tránh - IEnumerable từ database
var products = _context.Products.ToList()
    .Where(p => p.Price > 100); // Load all, then filter

Các câu hỏi so sánh khác

var vs dynamic

Aspectvardynamic
Type checkingCompile-timeRuntime
IntelliSense✅ Yes❌ No
PerformanceFastSlower
Use caseType known at compileLate binding

const vs readonly

Aspectconstreadonly
EvaluationCompile-timeRuntime
ValueMust be known at compileSet at runtime
StaticAlways staticCan be instance-level
Use caseCompile-time constantsRuntime constants

string vs StringBuilder

AspectstringStringBuilder
TypeImmutableMutable
MemoryNew allocation per changeDynamic buffer
Use caseSmall strings, no changesLarge strings, many concatenations

Task.WhenAll vs await in loop

// ❌ Sequential - Chậm
foreach (var url in urls)
{
    var response = await httpClient.GetAsync(url);
}

// ✅ Parallel - Nhanh hơn
var tasks = urls.Select(url => httpClient.GetAsync(url));
var responses = await Task.WhenAll(tasks);