issue 117apr 27mmxxvi
est. 2017
Sun, 27 Apr 2026
vol. IX · no. 117
PapersAdda
placement intelligence, since 2017
640+ briefs · 24 campuses · by reservation
verified offers · sourced from r/developersIndia
razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1

.NET Interview Questions and Answers 2026

22 min read
Interview Questions
Updated: 8 Jun 2026
Aditya Sharma
Aditya's Edit

PapersAdda 2026 Placement Cycle

By Aditya Sharma·Founder & Editor, PapersAdda

What changed in 2026 drives

Mass-recruiter offer letters are flatter for 2026 batch - the 4-5 LPA ASE band has barely budged in three years while inflation eats real wages. Premium tracks (Digital, Pro, Elite, Specialist) are still where the differential lives, and they are entirely test-driven. If you are aiming higher than the default offer, the coding round is not optional pageantry - it is the entire interview.

What I'd actually study for this

  • 01Two solid coding-round answers (1 medium-hard DSA each, with edge-case discussion) > five half-baked ones
  • 02One real project you can defend end-to-end - file paths, design decisions, and what you would change
  • 03One DBMS schema you actually built (not a textbook ER diagram), with at least 3 join-heavy queries written from memory
  • 04Three behavioural STAR stories: failure recovered, conflict handled, ownership taken

Where most candidates trip up

The single biggest mistake is treating company-specific guides as primary prep and DSA as secondary. It is the opposite. Mass recruiters use the test as a filter, but premium tracks at every IT services company use coding to allocate offer band. Spend 70% of prep time on DSA + system fundamentals, 20% on company-specific patterns, 10% on HR rehearsal. Reverse that ratio and you collect the default offer.

Editorial commentary by Aditya Sharma · written for PapersAdda · not generated, not aggregated.

.NET is Microsoft's cross-platform, open-source developer platform. Candidates report that C# language fundamentals, CLR internals (GC, value vs reference types), async/await and Task, LINQ, generics, delegates and events, Entity Framework Core, and .NET 8 features are the most heavily tested topics in .NET developer and full-stack engineer interviews. This guide covers 50 questions. Confirm the .NET version at your target company on their official careers portal.

Table of Contents

  1. C# Language Fundamentals
  2. CLR, Memory, and GC
  3. Async/Await and Concurrency
  4. LINQ
  5. Generics, Delegates, and Events
  6. Object-Oriented Patterns
  7. Entity Framework Core
  8. .NET 8 and Modern C#
  9. 5-Question Mock Test
  10. Frequently Asked Questions

C# Language Fundamentals

Q1. What is the difference between value types and reference types? Easy

// Value types: stored on stack, copied on assignment
int a = 5;
int b = a;  // b is a copy of a
b = 10;
Console.WriteLine(a);  // 5 (a unchanged)

// struct is a value type
struct Point { public int X, Y; }
Point p1 = new Point { X = 1, Y = 2 };
Point p2 = p1;    // copy
p2.X = 99;
Console.WriteLine(p1.X);  // 1 (p1 unchanged)

// Reference types: stored on heap, reference copied
class Box { public int Value; }
Box x = new Box { Value = 5 };
Box y = x;      // y is a reference to the same object
y.Value = 10;
Console.WriteLine(x.Value);  // 10 (same object)

// Value types: int, double, float, bool, char, decimal, long, struct, enum
// Reference types: class, interface, delegate, array, string, object

Q2. What is the difference between == and Equals() in C#? Medium

// Value types: == compares values (same result as Equals)
int x = 5, y = 5;
Console.WriteLine(x == y);       // True
Console.WriteLine(x.Equals(y));  // True

// Reference types: == compares references by default
object a = new object();
object b = new object();
Console.WriteLine(a == b);       // False (different objects)

// string: == is overloaded to compare content
string s1 = "hello";
string s2 = new string(new char[] {'h','e','l','l','o'});
Console.WriteLine(s1 == s2);      // True (content)
Console.WriteLine(object.ReferenceEquals(s1, s2));  // False (different objects)

// Override Equals and == for custom types
class Money {
    public decimal Amount { get; init; }
    public string Currency { get; init; }

    public override bool Equals(object? obj) =>
        obj is Money other && Amount == other.Amount && Currency == other.Currency;

    public override int GetHashCode() => HashCode.Combine(Amount, Currency);

    public static bool operator ==(Money left, Money right) =>
        left?.Equals(right) ?? right is null;
    public static bool operator !=(Money left, Money right) => !(left == right);
}

Q3. What are nullable value types and nullable reference types? Medium

// Nullable value types (pre-C# 8): Nullable<T> or T?
int? nullableInt = null;
double? nullableDouble = 3.14;

bool hasValue = nullableInt.HasValue;  // false
int value = nullableInt.GetValueOrDefault(); // 0
int value2 = nullableInt ?? -1;         // -1 (null coalescing)

// Null coalescing assignment
nullableInt ??= 42; // assign only if null

// C# 8 nullable reference types (warnings, not runtime enforcement)
// Enable in project: <Nullable>enable</Nullable>
string? maybeNull = null;
string notNull = "always here";

// Null-conditional operator
string? name = GetUser()?.Name;
int length = name?.Length ?? 0;

// Null forgiving operator (suppress warning, use sparingly)
string forceNotNull = maybeNull!;

Q4. What is the difference between abstract class and interface in C#? Medium

// Abstract class: partial implementation, single inheritance
public abstract class Shape
{
    public string Color { get; set; } = "white";  // state

    // Abstract: must override
    public abstract double Area();
    public abstract double Perimeter();

    // Virtual: may override
    public virtual string Describe() => $"{Color} shape with area {Area():F2}";
}

// Interface: contract only (C# 8+ can have default implementations)
public interface IDrawable
{
    void Draw();
    // C# 8 default implementation
    void DrawOutline() => Draw(); // optional override
}

public interface IResizable
{
    void Scale(double factor);
}

// Class can implement multiple interfaces, inherit one abstract class
public class Circle : Shape, IDrawable, IResizable
{
    public double Radius { get; set; }
    public override double Area() => Math.PI * Radius * Radius;
    public override double Perimeter() => 2 * Math.PI * Radius;
    public void Draw() => Console.WriteLine($"Drawing circle r={Radius}");
    public void Scale(double factor) => Radius *= factor;
}
AspectAbstract ClassInterface
InheritanceSingleMultiple
State (fields)YesNo (properties only)
ConstructorYesNo
Access modifiersAnyPublic by default
Default implVirtual methodsC# 8+ default interface methods

Q5. What are C# records and when do you use them? Medium

Records (C# 9+) are immutable reference types with value-based equality, copy constructor, and deconstruction built in.

// Record: auto-implements Equals, GetHashCode, ToString, deconstruction
public record Person(string FirstName, string LastName);

var p1 = new Person("John", "Doe");
var p2 = new Person("John", "Doe");
Console.WriteLine(p1 == p2);     // True (value equality)
Console.WriteLine(p1.Equals(p2)); // True

// Non-destructive mutation with 'with'
var p3 = p1 with { LastName = "Smith" };
Console.WriteLine(p1.LastName);  // "Doe" (original unchanged)

// Deconstruction
var (first, last) = p1;

// Record struct (value type, C# 10)
public record struct Point(int X, int Y);

// Use records for: DTOs, value objects, domain models that should be immutable
// Do not use for: entities with identity (use class), mutable objects

CLR, Memory, and GC

Q6. How does the .NET Garbage Collector work? Advanced

The .NET GC uses a generational, mark-and-compact algorithm.

Generations:

  • Gen 0: new short-lived objects. Collected most frequently (cheapest).
  • Gen 1: objects that survived Gen 0. Buffer between Gen 0 and Gen 2.
  • Gen 2: long-lived objects (statics, large objects). Collected least frequently.
  • Large Object Heap (LOH): objects >= 85KB. Only compacted on demand.

Collection phases:

  1. Mark: GC marks all live objects reachable from GC roots (stack variables, static fields, GC handles)
  2. Compact: moves surviving objects together (eliminates fragmentation), updates references
  3. Sweep (for LOH): frees memory without moving objects
// Force collection (avoid in production - disruptive)
GC.Collect(2, GCCollectionMode.Forced, blocking: true);

// Check memory
long bytes = GC.GetTotalMemory(forceFullCollection: false);
GCMemoryInfo info = GC.GetGCMemoryInfo();

// Weak reference: does not prevent GC
var weak = new WeakReference<ExpensiveObject>(obj);
if (weak.TryGetTarget(out var target)) { /* still alive */ }

// IDisposable pattern for unmanaged resources
public class FileWrapper : IDisposable
{
    private FileStream? _stream;
    private bool _disposed;

    public FileWrapper(string path) => _stream = File.OpenRead(path);

    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing) _stream?.Dispose();
            _disposed = true;
        }
    }
}

// Using statement ensures Dispose is called
using var file = new FileWrapper("data.txt");
// Or: using (var file = new FileWrapper("data.txt")) { ... }

Q7. What is the difference between the stack and the heap? Medium

The stack is a LIFO structure used for method call frames, local variables of value types, and references. It is thread-local, fast, automatically managed (push/pop with method calls/returns), and limited in size (typically 1MB per thread).

The heap is a shared memory region for reference type objects. Managed by the GC. Objects persist until no references remain. Slower than stack due to allocation overhead and GC.

void Method()
{
    int x = 42;           // stack: value type
    double y = 3.14;      // stack: value type
    object obj = new();   // stack: reference | heap: object data
    string s = "hello";   // stack: reference | heap: interned string
}
// On method return: x, y, obj reference, s reference are popped from stack
// obj and s on heap eligible for GC if no other references

Q8. What is boxing and unboxing? Easy

Boxing converts a value type to a reference type (object or interface). Unboxing extracts the value type from the object. Both cause allocations and should be avoided in performance-critical paths.

int i = 42;
object boxed = i;       // boxing: allocates heap object wrapping int
int unboxed = (int)boxed; // unboxing: copies int back from heap

// Common boxing scenarios (avoid)
ArrayList list = new ArrayList();
list.Add(42);           // boxes int
int x = (int)list[0];  // unboxes int

// Use generic collections instead (no boxing)
List<int> nums = new List<int>();
nums.Add(42);           // no boxing

// Interface boxing
IComparable c = 42;     // boxes int (implements IComparable)

Async/Await and Concurrency

Q9. How does async/await work under the hood? Advanced

The C# compiler transforms async methods into a state machine. Each await expression becomes a state transition point.

// Written code
public async Task<string> GetDataAsync()
{
    var result = await httpClient.GetStringAsync("https://api.example.com/data");
    return result.ToUpper();
}

// Conceptually compiled to (simplified):
public Task<string> GetDataAsync()
{
    var machine = new GetDataStateMachine(this);
    machine.MoveNext();
    return machine.Builder.Task;
}

struct GetDataStateMachine : IAsyncStateMachine
{
    private int _state;
    private AsyncTaskMethodBuilder<string> _builder;
    private TaskAwaiter<string> _awaiter;

    public void MoveNext()
    {
        if (_state == 0)
        {
            _awaiter = httpClient.GetStringAsync("...").GetAwaiter();
            if (!_awaiter.IsCompleted)
            {
                _state = 1;
                _builder.AwaitUnsafeOnCompleted(ref _awaiter, ref this);
                return; // returns to caller; no thread blocked
            }
        }
        // _state == 1: continuation
        string result = _awaiter.GetResult();
        _builder.SetResult(result.ToUpper());
    }
}

Q10. What is the difference between Task.Run, Task.Factory.StartNew, and async/await? Medium

// Task.Run: schedule CPU-bound work on ThreadPool
// Use for: CPU-heavy computation, never for async IO
var result = await Task.Run(() => ExpensiveComputation());

// async/await for IO-bound: does NOT create a thread
// The thread is released while waiting for IO
public async Task<string> FetchDataAsync()
{
    // No thread blocked during this await
    var response = await httpClient.GetAsync("https://api.example.com");
    return await response.Content.ReadAsStringAsync();
}

// Task.WhenAll: run multiple tasks concurrently
var (user, posts, settings) = await (
    GetUserAsync(),
    GetPostsAsync(),
    GetSettingsAsync()
);
// Or:
var tasks = new[] { task1, task2, task3 };
await Task.WhenAll(tasks);

// Task.WhenAny: first to complete wins
var fastestTask = await Task.WhenAny(task1, task2, task3);
var result = await fastestTask;

// CancellationToken: cooperative cancellation
public async Task<string> GetDataAsync(CancellationToken ct)
{
    var response = await httpClient.GetAsync("...", ct);
    ct.ThrowIfCancellationRequested(); // check periodically in CPU work
    return await response.Content.ReadAsStringAsync(ct);
}

Q11. Predict the output: Advanced

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("1");
        var t = Task.Run(() => { Console.WriteLine("2"); return 42; });
        Console.WriteLine("3");
        var result = await t;
        Console.WriteLine($"4: {result}");
    }
}

Output (most likely):

1
3
2
4: 42

Explanation: "1" prints synchronously. Task.Run schedules the lambda on the ThreadPool but the current thread continues immediately. "3" prints before the thread pool thread gets to run. "2" prints from the ThreadPool thread (may interleave with "3" in theory, but "3" typically wins in practice on a free thread). await t suspends until the task completes; then "4: 42" prints. The exact order of "2" and "3" depends on scheduling, but "2" after "3" is the common case.

Q12. What are common async/await mistakes? Medium

// MISTAKE 1: async void (unhandled exceptions crash the process)
// WRONG:
async void LoadData() { await FetchAsync(); }
// CORRECT: use async Task for all async methods except event handlers
async Task LoadDataAsync() { await FetchAsync(); }

// MISTAKE 2: .Result or .Wait() (deadlock in synchronization contexts)
// WRONG (deadlocks in ASP.NET Core / WPF if called from UI thread):
var result = GetDataAsync().Result;
// CORRECT:
var result = await GetDataAsync();

// MISTAKE 3: not configuring ConfigureAwait(false) in libraries
// In library code (not ASP.NET Core endpoints):
var data = await SomeIoCallAsync().ConfigureAwait(false);
// Prevents capturing the synchronization context (improves performance)

// MISTAKE 4: sequential awaits instead of concurrent
// SLOW: sequential
var user = await GetUserAsync();
var posts = await GetPostsAsync();

// FAST: concurrent
var userTask = GetUserAsync();
var postsTask = GetPostsAsync();
var (user, posts) = (await userTask, await postsTask);

// MISTAKE 5: async over sync (wrapping sync code in async without reason)
// WRONG:
async Task<int> GetCountAsync() => await Task.FromResult(42);
// CORRECT:
int GetCount() => 42;
Task<int> GetCountAsync() => Task.FromResult(42);

LINQ

Q13. What are LINQ deferred vs immediate execution methods? Medium

int[] numbers = { 1, 2, 3, 4, 5 };

// Deferred execution: returns IEnumerable, executes on enumeration
var query = numbers.Where(n => n > 2).Select(n => n * 2); // no execution yet
foreach (var n in query) Console.Write(n); // executes here: 6 8 10

// Modifying source after query definition affects result
var list = new List<int> { 1, 2, 3 };
var q = list.Where(n => n > 1); // deferred
list.Add(4);
Console.WriteLine(string.Join(",", q)); // 2, 3, 4 (4 included)

// Immediate execution: executes and materializes results
var list1 = numbers.Where(n => n > 2).ToList();  // executes NOW
var arr = numbers.Where(n => n > 2).ToArray();
var count = numbers.Count(n => n > 2);            // executes NOW
var first = numbers.First(n => n > 3);            // executes NOW
var dict = numbers.ToDictionary(n => n, n => n * n);

// Multiple enumeration issue
var deferred = numbers.Where(n => { Console.Write("Q "); return n > 2; });
deferred.ToList();  // prints "Q Q Q Q Q"
deferred.ToList();  // prints "Q Q Q Q Q" AGAIN (re-executes)
var materialized = deferred.ToList(); // one execution
materialized.ToList(); // no re-execution

Q14. What are the key LINQ operators? Easy

var people = new List<Person>
{
    new("Alice", 30, "Engineering"),
    new("Bob", 25, "Marketing"),
    new("Charlie", 30, "Engineering"),
    new("Diana", 28, "Marketing"),
};

// Filtering
var engineers = people.Where(p => p.Department == "Engineering");

// Projection
var names = people.Select(p => p.Name);
var nameAge = people.Select(p => new { p.Name, p.Age });

// Ordering
var byAge = people.OrderBy(p => p.Age).ThenBy(p => p.Name);
var byAgeDesc = people.OrderByDescending(p => p.Age);

// Grouping
var byDept = people.GroupBy(p => p.Department);
foreach (var group in byDept)
{
    Console.WriteLine($"{group.Key}: {string.Join(", ", group.Select(p => p.Name))}");
}

// Aggregation
var totalAge = people.Sum(p => p.Age);
var avgAge = people.Average(p => p.Age);
var oldest = people.Max(p => p.Age);
var count = people.Count(p => p.Age > 27);

// Joining
var dept = new[] { new Dept(1,"Engineering"), new Dept(2,"Marketing") };
var joined = people.Join(dept, p => p.DeptId, d => d.Id, (p, d) => new { p.Name, d.Name });

// Flattening
var orders = customers.SelectMany(c => c.Orders);

// Partitioning
var first3 = people.Take(3);
var skip2 = people.Skip(2);
var page2 = people.Skip(20).Take(20); // page 2 of 20

Q15. What is the difference between IEnumerable and IQueryable? Advanced

// IEnumerable<T>: in-memory collection, LINQ to Objects
// Executes in C# memory; fetches all data first
IEnumerable<Post> posts = dbContext.Posts.AsEnumerable();
var filtered = posts.Where(p => p.Status == "published"); // C# filter on ALL posts in memory

// IQueryable<T>: builds expression tree, translated to SQL
// Executes in database; only fetches filtered data
IQueryable<Post> qPosts = dbContext.Posts; // no SQL yet
var qFiltered = qPosts.Where(p => p.Status == "published"); // adds WHERE to SQL
var result = qFiltered.Take(10).ToList(); // executes: SELECT ... WHERE status='published' LIMIT 10

// Common mistake: AsEnumerable() too early
// WRONG: fetches entire table, filters in C#
dbContext.Posts.AsEnumerable().Where(p => p.Status == "published").Take(10);

// CORRECT: filter in database
dbContext.Posts.Where(p => p.Status == "published").Take(10);

// Use AsEnumerable() intentionally when: using C# functions SQL cannot translate
dbContext.Posts
    .Where(p => p.Status == "published") // SQL WHERE
    .AsEnumerable()
    .Where(p => MyCustomCSharpFilter(p)); // C# filter after DB fetch

Generics, Delegates, and Events

Q16. What are generics and why are they used? Easy

// Generic class: type-safe without boxing
public class Stack<T>
{
    private readonly List<T> _items = new();

    public void Push(T item) => _items.Add(item);
    public T Pop()
    {
        if (_items.Count == 0) throw new InvalidOperationException("Stack empty");
        var last = _items[^1];
        _items.RemoveAt(_items.Count - 1);
        return last;
    }
    public int Count => _items.Count;
}

Stack<int> intStack = new();
intStack.Push(1);
int x = intStack.Pop(); // no cast needed

// Generic method
public static T Max<T>(T a, T b) where T : IComparable<T>
    => a.CompareTo(b) >= 0 ? a : b;

// Generic constraints
public class Repository<T> where T : class, IEntity, new()
{
    public T Create() => new T();
}

// Common constraints:
// where T : class          → reference type
// where T : struct         → value type
// where T : new()          → has parameterless constructor
// where T : IMyInterface   → implements interface
// where T : BaseClass      → inherits from BaseClass
// where T : notnull        → non-nullable

Q17. What are delegates, Func, Action, and Predicate? Medium

// Delegate: type-safe function pointer
public delegate int MathOperation(int x, int y);

MathOperation add = (x, y) => x + y;
MathOperation multiply = (x, y) => x * y;
int result = add(3, 4); // 7

// Func<T>: built-in delegate for methods with return value
Func<int, int, int> add2 = (x, y) => x + y;
Func<string, bool> isLong = s => s.Length > 10;
Func<int> getRandom = () => new Random().Next(100);

// Action<T>: built-in delegate for void methods
Action<string> print = Console.WriteLine;
Action<int, int> swap = (a, b) => { /* swap */ };
Action doWork = () => Console.WriteLine("Working");

// Predicate<T>: Func<T, bool> shorthand
Predicate<int> isEven = n => n % 2 == 0;
bool even = isEven(4); // true

// Multicast delegate: += to combine
Action log = () => Console.WriteLine("Log");
Action audit = () => Console.WriteLine("Audit");
Action combined = log + audit;
combined(); // invokes both

// Events: delegate-based notification
public class Button
{
    public event EventHandler? Clicked;

    protected void OnClicked() => Clicked?.Invoke(this, EventArgs.Empty);

    public void Simulate() => OnClicked();
}

var btn = new Button();
btn.Clicked += (sender, e) => Console.WriteLine("Button clicked!");
btn.Simulate(); // triggers the event

Object-Oriented Patterns

Q18. What are the key OOP concepts in C#? Easy

// Encapsulation: hide implementation
class BankAccount
{
    private decimal _balance;
    public decimal Balance => _balance; // read-only

    public bool Withdraw(decimal amount)
    {
        if (amount > _balance) return false;
        _balance -= amount;
        return true;
    }
}

// Inheritance
class SavingsAccount : BankAccount
{
    public decimal InterestRate { get; init; }
    public void ApplyInterest() { /* add interest */ }
}

// Polymorphism
abstract class Animal
{
    public abstract string Sound();
    public virtual string Describe() => $"I am a {GetType().Name} and I say {Sound()}";
}

class Dog : Animal { public override string Sound() => "Woof"; }
class Cat : Animal { public override string Sound() => "Meow"; }

Animal[] animals = { new Dog(), new Cat() };
foreach (var a in animals) Console.WriteLine(a.Sound()); // runtime dispatch

// Abstraction: expose only what's needed
interface IPaymentProcessor
{
    Task<PaymentResult> ProcessAsync(PaymentRequest request);
}

Q19. What are C# properties and auto-properties? Easy

class Product
{
    // Auto-property
    public string Name { get; set; } = "";

    // Init-only (set only in constructor/initializer, C# 9)
    public int Id { get; init; }

    // Computed property
    private decimal _price;
    public decimal Price
    {
        get => _price;
        set
        {
            if (value < 0) throw new ArgumentOutOfRangeException(nameof(value));
            _price = value;
        }
    }

    // Expression-bodied computed
    public string DisplayName => $"{Id}: {Name} (${Price:F2})";

    // Required property (C# 11)
    public required string Sku { get; set; }
}

// Object initializer
var p = new Product { Id = 1, Name = "Widget", Price = 9.99m, Sku = "WDG-001" };

Entity Framework Core

Q20. How does Entity Framework Core work and what are migrations? Medium

// DbContext
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}

    public DbSet<Post> Posts => Set<Post>();
    public DbSet<User> Users => Set<User>();

    protected override void OnModelCreating(ModelBuilder mb)
    {
        mb.Entity<Post>(e => {
            e.HasKey(p => p.Id);
            e.Property(p => p.Title).IsRequired().HasMaxLength(200);
            e.HasIndex(p => p.Slug).IsUnique();
            e.HasOne(p => p.Author).WithMany(u => u.Posts).HasForeignKey(p => p.AuthorId);
        });
    }
}

// Registration in DI
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("Default")));

// Querying
var posts = await context.Posts
    .Include(p => p.Author)
    .ThenInclude(a => a.Profile)
    .Where(p => p.Status == "published")
    .OrderByDescending(p => p.CreatedAt)
    .Take(10)
    .ToListAsync();

// Saving
var post = new Post { Title = "New Post", AuthorId = userId };
context.Posts.Add(post);
await context.SaveChangesAsync();

// Update
var existing = await context.Posts.FindAsync(id);
existing!.Title = "Updated Title";
await context.SaveChangesAsync(); // change tracking detects modification

// Migrations
// dotnet ef migrations add AddSlugsToPost
// dotnet ef database update

.NET 8 and Modern C#

Q21. What are the key C# 12 and .NET 8 features? Medium

// C# 12: Primary constructors (classes and structs)
public class UserService(IUserRepository repo, ILogger<UserService> logger)
{
    public async Task<User?> GetAsync(int id)
    {
        logger.LogInformation("Getting user {Id}", id);
        return await repo.GetByIdAsync(id);
    }
}

// C# 12: Collection expressions
int[] arr = [1, 2, 3];
List<string> list = ["a", "b", "c"];
Span<int> span = [1, 2, 3];
int[] combined = [..arr, 4, 5]; // spread operator

// C# 11: Required members
public class Config
{
    public required string ConnectionString { get; init; }
    public required string ApiKey { get; init; }
}
new Config { ConnectionString = "...", ApiKey = "..." }; // both required

// C# 10: Record structs
public readonly record struct Point2D(float X, float Y);

// .NET 8: Frozen collections (read-only, faster lookups)
using System.Collections.Frozen;
FrozenDictionary<string, int> dict = new Dictionary<string, int>
    { ["a"] = 1, ["b"] = 2 }.ToFrozenDictionary();

// .NET 8: TimeProvider (testable time)
public class OrderService(TimeProvider timeProvider)
{
    public Order Create() => new Order { CreatedAt = timeProvider.GetUtcNow() };
}

// .NET 8: Keyed DI services
builder.Services.AddKeyedSingleton<ICache, RedisCache>("redis");
builder.Services.AddKeyedSingleton<ICache, MemoryCache>("memory");

class MyService([FromKeyedServices("redis")] ICache cache) { }

Q22. What are pattern matching improvements in modern C#? Medium

object obj = 42;

// Type pattern
if (obj is int n) Console.WriteLine($"Int: {n}");

// Switch expression
string result = obj switch
{
    int i when i < 0 => "negative",
    int i => $"positive: {i}",
    string s => $"string: {s}",
    null => "null",
    _ => "other"
};

// Property pattern
var point = new Point(3, 4);
bool isOrigin = point is { X: 0, Y: 0 };
string quadrant = point switch
{
    { X: > 0, Y: > 0 } => "Q1",
    { X: < 0, Y: > 0 } => "Q2",
    { X: < 0, Y: < 0 } => "Q3",
    { X: > 0, Y: < 0 } => "Q4",
    _ => "on axis"
};

// List patterns (C# 11)
int[] numbers = [1, 2, 3, 4, 5];
bool matched = numbers is [1, 2, ..var rest]; // rest = [3,4,5]

// Positional deconstruction patterns
var (x, y) = new Point(3, 4);
bool isQ1 = new Point(3, 4) is ( > 0, > 0 );

5-Question Mock Test

Q1. What is the difference between Task.Run() and await? When do you use Task.Run() for a network call?

Q2. Explain LINQ deferred execution. What is the potential problem with multiple enumeration?

Q3. What is the difference between IEnumerable<T> and IQueryable<T> when used with Entity Framework?

Q4. What does this code output?

int x = 10;
int y = x;
y = 20;
Console.WriteLine(x);

var s1 = new List<int> { 1 };
var s2 = s1;
s2.Add(2);
Console.WriteLine(s1.Count);

Q5. What is boxing and why does it hurt performance?

Answers:

A1. Task.Run() schedules work on a ThreadPool thread, suitable for CPU-bound computation. await suspends the current method and returns control to the caller while waiting for an IO-bound operation (no thread consumed during the wait). You should NOT use Task.Run() for network calls: the network call itself is async IO; wrapping it in Task.Run() wastes a thread waiting.

A2. Deferred execution means the LINQ query runs only when iterated, not when defined. Multiple enumeration re-runs the query each time. Problem: if the query has side effects, DB queries, or the underlying data changes, results may differ between enumerations. Fix: materialize with ToList() or ToArray() when the result will be iterated multiple times.

A3. IEnumerable<T> executes in C# memory: EF fetches ALL matching rows from the database, then applies further LINQ in memory. IQueryable<T> translates LINQ to SQL: only the final filtered/projected result set is fetched. Using IEnumerable after IQueryable (via AsEnumerable()) forces a DB round trip for everything before that point.

A4. Output: 10 then 2. y = x copies the int value (value type). Modifying y does not affect x. s2 = s1 copies the reference (reference type). Both s1 and s2 point to the same list; s2.Add(2) mutates the shared list, so s1.Count is 2.

A5. Boxing wraps a value type in a heap-allocated object. It causes a heap allocation per box, puts pressure on the GC, and requires a cast (unboxing) to retrieve the value. Use generic collections (List<int>) instead of non-generic ones (ArrayList) to avoid boxing.


Frequently Asked Questions

What is the difference between .NET Framework and .NET (Core/5+)?

.NET Framework is Windows-only, maintained but no longer actively developed. .NET (previously .NET Core, now just .NET from version 5 onwards) is cross-platform (Windows, Linux, macOS), open-source, and the future of the platform. Candidates report interviewers often ask about the migration path from .NET Framework to .NET 8.

What is the CLR?

The Common Language Runtime is the execution engine for .NET. It provides JIT compilation (converts IL to native code), garbage collection, type safety, exception handling, and thread management. All .NET languages (C#, F#, VB.NET) compile to CIL (Common Intermediate Language) bytecode, then the CLR JIT-compiles it to native machine code at runtime. .NET 8 includes ReadyToRun compilation for faster startup.

What is dependency injection in ASP.NET Core?

ASP.NET Core has a built-in IoC container. Services are registered in Program.cs with lifetimes: AddTransient (new instance per injection), AddScoped (one per HTTP request), AddSingleton (one for the app lifetime). They are injected via constructor injection in controllers and services. Candidates report DI lifetime questions (especially the captive dependency problem: injecting transient into singleton) are common in interviews.

What is the internal mesh of related topics?

Methodology applied to this articlelast verified 8 Jun 2026
Sources used
Public exam-pattern documents, official recruiter pages, and verified candidate reports on r/developersIndia and LinkedIn.
Verification window
Page last edited 8 Jun 2026 by Aditya Sharma. Numbers and patterns sanity-checked against the most recent 2026 cycle drives we tracked.
What we did NOT do
  • No fabricated salary numbers or success rates. If we quote a range, it's sourced.
  • No noun-substituted templates. This article was not generated by swapping company names in a stock prompt.
  • No paid placements, sponsored coaching links, or affiliate-shilled course pushes.
Verification policy: /editorial-standards/. Found something incorrect? Submit a correction - we respond within 48 hours.

Explore this topic cluster

More resources in Interview Questions

Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.

Paid contributor programme

Sat this this year? Share your story, earn ₹500.

First-person experience reports help future candidates prep smarter. We pay verified contributors ₹500 via UPI per accepted story - with byline.

Submit your story →

Ready to practice?

Take a free timed mock test

Put what you learned into practice. Our mock tests match the 2026 pattern with timer, navigator, reveal, and score breakdown. No signup.

Start Free Mock Test →

Related Articles

More from PapersAdda

Share this guide: