Chapter 2 — C# Fundamentals (60 Questions)

Topics:

C# Language Basics

  1. What is the difference between value types and reference types?
  2. Stack vs heap memory
  3. Class vs struct
  4. Record vs class
  5. Interface vs abstract class
  6. Access modifiers
  7. Static classes
  8. Const vs readonly
  9. Nullable reference types
  10. Pattern matching

Object-Oriented Programming

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Method overloading
  5. Method overriding
  6. Virtual methods
  7. Sealed classes
  8. Composition vs inheritance

Advanced C#

  1. Delegates
  2. Events
  3. Lambda expressions
  4. LINQ
  5. Generics
  6. Extension methods
  7. Async/await
  8. Task vs Thread
  9. CancellationToken
  10. Exception handling
  11. Garbage collection
  12. IDisposable

1. What is the difference between value types and reference types in C#?

Interview Answer

In C#, types are divided into value types and reference types.

Value Types

A value type stores the actual data directly.

Examples:

int age = 50;

double price = 100.5;

bool isActive = true;

struct Point { }

When a value type is assigned to another variable, a copy of the value is created.

Example:

int a = 10;

int b = a;

b = 20;

Console.WriteLine(a); // 10

a remains unchanged because b has its own copy.


Reference Types

A reference type stores a reference to an object in memory.

Examples:

class Person

{

    public string Name { get; set; }

}

Person p1 = new Person();

p1.Name = "John";

Person p2 = p1;

p2.Name = "Mike";

Console.WriteLine(p1.Name);

Output:

Mike

Both variables reference the same object.


Common Value Types

Common Reference Types


Follow-up Question

Q: Are value types always stored on the stack?

Answer

Not necessarily.

A common misconception is:

Value types = stack
Reference types = heap

The reality is more complicated.

The actual memory location depends on:

For example:

class Employee

{

    public int Id;

}

Id is a value type, but it is stored inside the object on the heap.


2. What is the difference between stack and heap memory?

Interview Answer

The stack and heap are areas of memory managed by the .NET runtime.


Stack

The stack stores:

Example:

void Calculate()

{

    int x = 10;

}

x is a local variable.

The stack is:


Heap

The heap stores objects created dynamically.

Example:

Person person = new Person();

The object is created on the heap.

The heap is managed by the Garbage Collector.


Follow-up Question

Q: Who manages memory in .NET?

Answer

The .NET Garbage Collector (GC) automatically manages memory allocation and cleanup of managed objects.

Developers do not manually free memory like in C++.


3. What is a class in C#?

Interview Answer

A class is a blueprint for creating objects. It defines:

Example:

public class Customer

{

    public string Name { get; set; }

    public void Print()

    {

        Console.WriteLine(Name);

    }

}

Creating an object:

Customer customer = new Customer();

customer.Name = "John";

customer.Print();


Follow-up Question

Q: What is an object?

Answer

An object is an instance of a class.

Example:

Customer customer = new Customer();

Here:


4. What is the difference between a class and a struct?

Interview Answer

Both classes and structs can contain:

The main difference is that:

Class

Struct

Reference type

Value type

Stored as object reference

Stores actual value

Supports inheritance

Does not support class inheritance

Better for large objects

Better for small data structures


Example struct:

public struct Point

{

    public int X;

    public int Y;

}

Usage:

Point p = new Point();

p.X = 10;

p.Y = 20;


When should you use struct?

Use a struct for small immutable data objects:

Examples:

.NET examples:

DateTime

Guid

TimeSpan


5. What is the difference between a record and a class?

Interview Answer

A record is a special reference type designed for storing data where value equality is important.

Example:

public record Person(

    string Name,

    int Age

);

Two records with the same values are considered equal:

var p1 = new Person("John", 30);

var p2 = new Person("John", 30);

Console.WriteLine(p1 == p2);

Output:

True


A class compares references by default:

class Person

{

    public string Name { get; set; }

}

Two separate objects are not equal unless equality is overridden.


When to use records?

Good for:

Example:

public record OrderCreatedEvent(

    int OrderId,

    DateTime CreatedDate

);


6. What are access modifiers in C#?

Interview Answer

Access modifiers control visibility of classes and members.

The main modifiers are:


public

Accessible everywhere.

public string Name;


private

Accessible only inside the containing class.

private int salary;

Default for class members.


protected

Accessible inside the class and derived classes.

protected void Calculate()

{

}


internal

Accessible within the same assembly.

Useful for large applications with multiple projects.


protected internal

Accessible:


private protected

Accessible:


7. What is the difference between const and readonly?

Interview Answer

Both create values that cannot be changed after initialization, but they work differently.


const

A compile-time constant.

Example:

public const double Pi = 3.14159;

Rules:


readonly

Can be assigned:

Example:

public class Configuration

{

    public readonly string ConnectionString;

    public Configuration(string value)

    {

        ConnectionString = value;

    }

}


Comparison

const

readonly

Compile time

Runtime

Must initialize immediately

Constructor allowed

Always static

Instance or static

Limited types

Any type


8. What is a static class?

Interview Answer

A static class cannot be instantiated. It contains only static members.

Example:

public static class MathHelper

{

    public static int Add(int a, int b)

    {

        return a + b;

    }

}

Usage:

int result = MathHelper.Add(5,10);


Common uses


Follow-up Question

Q: Can a static class have a constructor?

Answer:

Yes, but only a static constructor.

Example:

static MathHelper()

{

    // initialization

}


9. What are nullable reference types in C#?

Interview Answer

Nullable reference types were introduced in C# 8 to help prevent null reference exceptions.

Before:

string name = null;

The compiler did not warn.

With nullable enabled:

string name = null;

Compiler warning.

You must explicitly allow null:

string? name = null;


Example:

public class User

{

    public string Name { get; set; } = "";

    public string? MiddleName { get; set; }

}


Benefit

They catch potential bugs during compilation instead of production.


10. What is boxing and unboxing in C#?

Interview Answer

Boxing converts a value type into an object.

Example:

int number = 10;

object obj = number;

The integer is wrapped inside an object.


Unboxing converts the object back to the value type.

Example:

int result = (int)obj;


Performance Consideration

Boxing creates an object on the heap, which can cause:

Avoid unnecessary boxing in performance-critical code.

11. What is encapsulation in C#?

Interview Answer

Encapsulation is the concept of hiding an object's internal state and requiring all interaction to happen through controlled methods or properties.

The purpose is:

Example:

public class BankAccount

{

    private decimal balance;

    public decimal Balance

    {

        get { return balance; }

    }

    public void Deposit(decimal amount)

    {

        if (amount > 0)

        {

            balance += amount;

        }

    }

}

The balance field cannot be modified directly:

account.balance = -1000; // Not allowed

The class controls how the value changes.


Follow-up Question

Q: How do you achieve encapsulation in C#?

Answer

Using:

Example:

private string password;

public void ChangePassword(string newPassword)

{

    // validation

}


12. What is inheritance in C#?

Interview Answer

Inheritance allows one class to reuse and extend another class.

The existing class is called the base class.

The new class is called the derived class.

Example:

public class Animal

{

    public string Name { get; set; }

    public void Eat()

    {

        Console.WriteLine("Eating");

    }

}

public class Dog : Animal

{

    public void Bark()

    {

        Console.WriteLine("Woof");

    }

}

Usage:

Dog dog = new Dog();

dog.Eat();

dog.Bark();

The Dog class inherits functionality from Animal.


Benefits


Follow-up Question

Q: Does C# support multiple inheritance?

Answer

No.

A class can inherit from only one class.

However, it can implement multiple interfaces.

Example:

class MyClass : BaseClass, ILogger, IDisposable

{

}


13. What is polymorphism in C#?

Interview Answer

Polymorphism means "many forms".

It allows objects to be treated as a common type while behaving differently depending on their actual implementation.

There are two main types:

  1. Compile-time polymorphism
  2. Runtime polymorphism

Compile-time polymorphism

Method overloading:

public class Calculator

{

    public int Add(int a, int b)

    {

        return a + b;

    }

    public double Add(double a, double b)

    {

        return a + b;

    }

}

Same method name, different parameters.


Runtime polymorphism

Method overriding:

public class Animal

{

    public virtual void Speak()

    {

        Console.WriteLine("Animal sound");

    }

}

public class Dog : Animal

{

    public override void Speak()

    {

        Console.WriteLine("Bark");

    }

}

Usage:

Animal animal = new Dog();

animal.Speak();

Output:

Bark


14. What is the difference between an abstract class and an interface?

Interview Answer

Both define contracts, but they have different purposes.


Abstract Class

An abstract class can contain:

Example:

public abstract class Shape

{

    public string Color { get; set; }

    public abstract double CalculateArea();

}


Interface

An interface defines a contract that classes must implement.

Example:

public interface ILogger

{

    void Log(string message);

}

Implementation:

public class FileLogger : ILogger

{

    public void Log(string message)

    {

        Console.WriteLine(message);

    }

}


Comparison

Abstract Class

Interface

Can contain implementation

Defines behavior contract

Can have fields

Cannot have instance fields

Supports single inheritance

Multiple interfaces allowed

Used for related classes

Used for capabilities


Senior Answer

I use interfaces when I need flexibility and loose coupling, especially with dependency injection. I use abstract classes when multiple classes share common implementation or state.


15. What are virtual, override, and abstract keywords?

Interview Answer

These keywords are used for runtime polymorphism.


virtual

Allows a method to be overridden.

Example:

public class Employee

{

    public virtual void CalculateSalary()

    {

        Console.WriteLine("Default calculation");

    }

}


override

Provides a new implementation in a derived class.

Example:

public class Manager : Employee

{

    public override void CalculateSalary()

    {

        Console.WriteLine("Manager calculation");

    }

}


abstract

Defines a method that must be implemented by derived classes.

Example:

public abstract class Employee

{

    public abstract decimal GetSalary();

}


Difference

Keyword

Purpose

virtual

Provides optional override

override

Replaces inherited behavior

abstract

Requires implementation


16. What is method overloading?

Interview Answer

Method overloading allows multiple methods with the same name but different parameters.

Example:

public class Printer

{

    public void Print(string text)

    {

    }

    public void Print(int number)

    {

    }

    public void Print(string text, int copies)

    {

    }

}

The compiler determines which method to call based on parameters.


Rules

Methods must differ by:

Return type alone is not enough.

Invalid:

int GetValue()

string GetValue()


17. What is method overriding?

Interview Answer

Method overriding allows a derived class to provide a different implementation of a method defined in the base class.

Example:

public class Payment

{

    public virtual void Process()

    {

        Console.WriteLine("Processing payment");

    }

}

public class CreditCardPayment : Payment

{

    public override void Process()

    {

        Console.WriteLine("Processing credit card");

    }

}


Usage:

Payment payment = new CreditCardPayment();

payment.Process();

Output:

Processing credit card


18. What is the difference between override and new keywords?

Interview Answer

Both can hide inherited methods, but they behave differently.


override

Uses runtime polymorphism.

Example:

class Dog : Animal

{

    public override void Speak()

    {

    }

}

The correct method is selected based on the actual object.


new

Hides the base method.

Example:

class Dog : Animal

{

    public new void Speak()

    {

    }

}

The method depends on the reference type.

Example:

Animal animal = new Dog();

animal.Speak();

With new, the base method may execute.


Senior Recommendation

Prefer override.

Use new only when intentionally hiding behavior.


19. What is a sealed class?

Interview Answer

A sealed class prevents inheritance.

Example:

public sealed class SecurityManager

{

}

This is not allowed:

public class MyManager : SecurityManager

{

}


Why use sealed classes?

Reasons:


Example in .NET

System.String

is sealed.

You cannot inherit from string.


20. Composition vs inheritance — which is better?

Interview Answer

Composition means building classes using other objects.

Inheritance means creating an "is-a" relationship.


Inheritance Example

class ElectricCar : Car

{

}

An electric car is a car.


Composition Example

class Car

{

    private Engine engine;

}

A car has an engine.


Senior Answer

I generally prefer composition over inheritance because it creates less coupling and makes systems easier to change. I use inheritance when there is a true "is-a" relationship and shared behavior.


Example

Instead of:

Bird

 |

FlyingBird

 |

NonFlyingBird

Use:

Bird

 |

IFlyBehavior

 |

Fly()

This follows the Strategy Pattern.

21. What is a delegate in C#?

Interview Answer

A delegate is a type that represents a reference to a method. It allows methods to be passed as parameters and stored in variables.

A delegate is similar to a function pointer in C++, but it is type-safe.

Example:

public delegate void NotificationHandler(string message);

public class NotificationService

{

    public void SendEmail(string message)

    {

        Console.WriteLine($"Email: {message}");

    }

}

Using the delegate:

NotificationService service = new();

NotificationHandler handler = service.SendEmail;

handler("Hello");

Output:

Email: Hello


Common Uses

Delegates are used for:


Follow-up Question

Q: Why not simply call the method directly?

Answer

Delegates provide flexibility because the caller can decide which method should execute.

Example:

handler = SendEmail;

handler = SendSms;

handler = SendPushNotification;

The same code can work with different behaviors.


22. What are Func, Action, and Predicate delegates?

Interview Answer

.NET provides built-in generic delegates so developers do not need to create custom delegates for common scenarios.


Action

Represents a method that returns void.

Example:

Action<string> print = message =>

{

    Console.WriteLine(message);

};

print("Hello");


Func

Represents a method that returns a value.

Example:

Func<int, int, int> add = (a, b) =>

{

    return a + b;

};

int result = add(5, 10);

Result:

15

The last generic parameter is always the return type.

Example:

Func<int, string>

means:

int input -> string output


Predicate

Represents a method returning bool.

Example:

Predicate<int> isEven = x => x % 2 == 0;

bool result = isEven(10);


Comparison

Delegate

Return

Action

void

Func

value

Predicate

bool


23. What are events in C#?

Interview Answer

Events provide a way for one object to notify other objects when something happens.

They are built on delegates.

Example:

public class OrderService

{

    public event Action<string>? OrderCreated;

    public void CreateOrder()

    {

        Console.WriteLine("Order created");

        OrderCreated?.Invoke("Order 123");

    }

}

Subscriber:

var service = new OrderService();

service.OrderCreated += message =>

{

    Console.WriteLine(message);

};


Common Examples

Events are used in:


Follow-up Question

Q: What is the difference between delegates and events?

Answer

A delegate can be called directly by anyone who has access to it.

An event restricts invocation so only the class that declares the event can raise it.

Events provide better encapsulation.


24. What are lambda expressions?

Interview Answer

A lambda expression is a short syntax for creating anonymous functions.

Example:

Traditional method:

int Add(int a, int b)

{

    return a + b;

}

Lambda:

Func<int,int,int> add = (a,b) => a+b;


Lambda Syntax

(parameters) => expression

Example:

x => x * 2

Multiple statements:

x =>

{

    var result = x * 2;

    return result;

}


Common Uses

Especially with LINQ:

var adults = users

    .Where(u => u.Age >= 18);


25. What is LINQ?

Interview Answer

LINQ (Language Integrated Query) allows querying data directly using C# syntax.

It works with:

Example:

var adults = users

    .Where(u => u.Age >= 18)

    .OrderBy(u => u.Name)

    .ToList();


Query Syntax

Example:

var result =

    from user in users

    where user.Age >= 18

    select user;


Benefits


26. What is the difference between IEnumerable and IQueryable?

Interview Answer

Both are used for querying collections, but they execute differently.


IEnumerable

Works with in-memory collections.

Example:

IEnumerable<User> users = list;

var result = users

    .Where(x => x.Active);

Filtering happens in memory.


IQueryable

Builds an expression tree that can be translated by a provider.

Example:

IQueryable<User> users = db.Users;

var result = users

    .Where(x => x.Active);

SQL may be generated:

SELECT *

FROM Users

WHERE Active = 1


Comparison

IEnumerable

IQueryable

In-memory execution

Remote execution

LINQ-to-Objects

LINQ-to-SQL

Less efficient for large data

Better for databases


Senior Interview Answer

For Entity Framework, I prefer IQueryable when filtering large database tables because the query can execute on the database server instead of loading unnecessary data into memory.


27. What is deferred execution in LINQ?

Interview Answer

Deferred execution means a LINQ query is not executed when it is created. It executes when the result is actually requested.

Example:

var query = users.Where(u => u.Active);

At this point, no filtering happens.

Execution happens here:

var result = query.ToList();


Benefits


Example

var query = users.Where(u => u.Age > 30);

query = query.Take(10);

var result = query.ToList();

Only the final query executes.


28. What are extension methods?

Interview Answer

Extension methods allow adding methods to existing types without modifying the original class.

Example:

public static class StringExtensions

{

    public static bool IsValidEmail(this string value)

    {

        return value.Contains("@");

    }

}

Usage:

string email = "test@test.com";

bool valid = email.IsValidEmail();


Requirements

Extension methods:


Common Examples

LINQ methods are extension methods:

.Where()

.Select()

.OrderBy()


29. What are generics in C#?

Interview Answer

Generics allow creating reusable, type-safe code without specifying a concrete type.

Example:

Without generics:

ArrayList list = new();

list.Add(10);

list.Add("hello");

Problems:


With generics:

List<int> numbers = new();

numbers.Add(10);

The compiler knows the type.


Generic Class Example

public class Repository<T>

{

    public void Add(T item)

    {

    }

}

Usage:

Repository<Customer> repository = new();


Benefits


30. What are generic constraints?

Interview Answer

Generic constraints restrict what types can be used with a generic class or method.

Example:

public class Repository<T>

    where T : class

{

}

Only reference types are allowed.


Common Constraints

Class constraint

where T : class

Reference types only.


Struct constraint

where T : struct

Value types only.


Interface constraint

where T : IDisposable

Must implement interface.


Base class constraint

where T : Entity

Must inherit from Entity.


Senior Example

Entity Framework uses generic patterns:

DbSet<T>

where generic types represent database entities.

31. What is async/await in C#?

Interview Answer

async and await are C# features used for asynchronous programming. They allow a method to perform long-running operations without blocking the calling thread.

Common scenarios:

Example:

public async Task<string> GetDataAsync()

{

    var result = await httpClient.GetStringAsync("https://api.example.com");

    return result;

}

The method starts an asynchronous operation and resumes when the operation completes.


Why use async/await?

Without async:

var data = GetDataFromDatabase();

The thread waits until the database responds.

With async:

var data = await GetDataFromDatabaseAsync();

The thread can do other work while waiting.


Senior Interview Answer

Async programming improves scalability, especially for server applications. Instead of blocking threads while waiting for I/O operations, the application can handle more concurrent requests.


32. How does async/await work internally?

Interview Answer

The compiler transforms an async method into a state machine.

Example:

public async Task ProcessAsync()

{

    await SaveDataAsync();

    SendEmail();

}

The compiler creates a state machine that:

  1. Starts execution.
  2. Reaches await.
  3. Returns control to the caller.
  4. Continues execution when the awaited task completes.

Important Point

async does not automatically create a new thread.

This is a common interview trap.

Example:

await database.GetDataAsync();

Usually uses asynchronous I/O, not another thread.


33. What is the difference between Task and Thread?

Interview Answer

A Thread represents an actual operating system thread.

A Task represents an asynchronous operation.


Thread Example

Thread thread = new Thread(() =>

{

    DoWork();

});

thread.Start();


Task Example

Task.Run(() =>

{

    DoWork();

});


Comparison

Thread

Task

OS-level resource

Higher-level abstraction

More expensive

Lightweight

Manual management

Managed by Task Scheduler

Good for dedicated work

Good for async operations


Senior Answer

In modern .NET applications, I usually prefer Task-based asynchronous programming because it provides better scalability and integrates with async/await.


34. What is Task.Run and when should you use it?

Interview Answer

Task.Run() schedules CPU-bound work on the thread pool.

Example:

await Task.Run(() =>

{

    CalculateLargeReport();

});


Good Use Cases

CPU-intensive operations:


Bad Use Case

Do not use:

await Task.Run(async () =>

{

    await database.SaveAsync();

});

For I/O operations, use the asynchronous API directly:

await database.SaveAsync();


35. What is the difference between Task, Task<T>, and ValueTask?

Interview Answer


Task

Represents an asynchronous operation without a result.

Example:

public async Task SaveAsync()

{

    await database.SaveAsync();

}


Task<T>

Represents an asynchronous operation returning a value.

Example:

public async Task<User> GetUserAsync()

{

    return await repository.GetUserAsync();

}


ValueTask<T>

A lightweight alternative when the result may already be available.

Example:

public ValueTask<User> GetUserAsync()

{

}


Senior Answer

Task is the default choice. ValueTask should only be used in performance-sensitive scenarios where avoiding allocations provides measurable benefits.


36. What is CancellationToken?

Interview Answer

CancellationToken allows an operation to be cancelled gracefully.

Example:

public async Task ProcessAsync(

    CancellationToken cancellationToken)

{

    while(true)

    {

        cancellationToken.ThrowIfCancellationRequested();

        await ProcessItemAsync();

    }

}


Creating cancellation:

var source = new CancellationTokenSource();

source.Cancel();


Common Uses


ASP.NET Core Example

public async Task<IActionResult> Get(

    CancellationToken cancellationToken)

{

    var data = await service.GetAsync(cancellationToken);

    return Ok(data);

}


37. How do you handle exceptions in C#?

Interview Answer

Exceptions are handled using:

Example:

try

{

    ProcessOrder();

}

catch(Exception ex)

{

    logger.LogError(ex, "Order failed");

}

finally

{

    Cleanup();

}


Best Practices

Catch specific exceptions

Good:

catch(SqlException ex)

{

}

Avoid:

catch(Exception ex)

{

}

unless you are handling it at a global level.


Do not hide exceptions

Bad:

catch(Exception)

{

}

This makes debugging difficult.


38. What are custom exceptions?

Interview Answer

Custom exceptions allow creating meaningful application-specific errors.

Example:

public class InsufficientFundsException

    : Exception

{

    public InsufficientFundsException(

        string message)

        : base(message)

    {

    }

}

Usage:

throw new InsufficientFundsException(

    "Account balance is too low");


When to use them?

Use custom exceptions when:

Examples:


39. What is IDisposable?

Interview Answer

IDisposable provides a mechanism for releasing unmanaged resources.

Examples:

Example:

public class FileProcessor : IDisposable

{

    public void Dispose()

    {

        // release resources

    }

}


Using:

using(var file = new FileStream("data.txt"))

{

    // work with file

}

The compiler automatically calls:

file.Dispose();


40. What is the using statement in C#?

Interview Answer

The using statement ensures that objects implementing IDisposable are properly cleaned up.

Example:

using(SqlConnection connection = new())

{

    connection.Open();

    // database work

}

Equivalent:

SqlConnection connection = new();

try

{

    connection.Open();

}

finally

{

    connection.Dispose();

}


Modern C# using declaration

Instead of:

using(var stream = new FileStream(...))

{

}

You can write:

using var stream = new FileStream(...);

The object is disposed at the end of the current scope.


Senior Interview Notes

Common mistakes candidates make:

Mistake 1

"async creates a new thread."

Incorrect.

Better:

"async allows non-blocking operations. A new thread may or may not be used depending on the operation."


Mistake 2

Using Task.Run() everywhere.

Better:

Use async APIs for I/O operations and Task.Run for CPU-bound work.


Mistake 3

Catching all exceptions.

Better:

Handle exceptions at the appropriate level and preserve useful diagnostic information.

41. How does Garbage Collection (GC) work in .NET?

Interview Answer

Garbage Collection is the automatic memory management system in .NET. It automatically identifies objects that are no longer reachable by the application and releases their memory.

Example:

public void Process()

{

    Customer customer = new Customer();

    customer.Name = "John";

}

After Process() finishes, the customer object may become unreachable. The Garbage Collector can later reclaim its memory.


Garbage Collector Process

The GC:

  1. Allocates memory for objects on the managed heap.
  2. Tracks object references.
  3. Detects objects that are no longer reachable.
  4. Releases memory.

Benefits


Follow-up Question

Q: Do developers need to manually free memory in C#?

Answer

No, managed memory is automatically handled by the Garbage Collector.

However, developers must manually release unmanaged resources using:

Examples:


42. What are GC generations in .NET?

Interview Answer

The .NET Garbage Collector uses generations to optimize memory management.

Objects are classified into:


Generation 0

Contains newly created short-lived objects.

Example:

var temp = new object();

Most objects die quickly, so collecting Gen 0 is fast.


Generation 1

Contains objects that survived a Gen 0 collection.


Generation 2

Contains long-lived objects.

Examples:


Why generations?

Because most objects have short lifetimes.

Instead of scanning the entire heap every time, GC focuses on newer objects first.


43. What is a memory leak in .NET?

Interview Answer

A memory leak occurs when objects are no longer needed but remain referenced, preventing the Garbage Collector from releasing them.

Example:

public class Cache

{

    private List<object> items = new();

    public void Add(object item)

    {

        items.Add(item);

    }

}

If objects are continuously added and never removed, memory usage grows.


Common Causes

1. Static references

Example:

static List<Customer> customers;

Static objects live for the lifetime of the application.


2. Event subscriptions

Example:

publisher.Event += handler;

If the subscriber is not removed:

publisher.Event -= handler;

the object may remain in memory.


3. Unreleased unmanaged resources

Example:


How to find memory leaks?

Tools:


44. What is a finalizer in C#?

Interview Answer

A finalizer is a special method called by the Garbage Collector before an object is removed from memory.

Example:

public class Resource

{

    ~Resource()

    {

        // cleanup

    }

}


Important Points

Finalizers:


Preferred approach

Use:

IDisposable

instead.

Example:

using(var connection = new SqlConnection())

{

}


45. What is the difference between IDisposable and finalizer?

Interview Answer

Both are related to resource cleanup, but they work differently.

IDisposable

Finalizer

Explicit cleanup

Automatic cleanup

Deterministic

Non-deterministic

Faster

Slower

Recommended

Last safety mechanism


Senior Answer

IDisposable should be used whenever possible because it gives developers control over when resources are released. Finalizers are only a backup mechanism for unmanaged resources.


46. What is reflection in C#?

Interview Answer

Reflection allows a program to inspect and interact with types at runtime.

It can:

Example:

Type type = typeof(Customer);

Console.WriteLine(type.Name);


Creating objects dynamically:

object instance =

    Activator.CreateInstance(type);


Common Uses

Examples:


Disadvantages

Reflection can be:


47. What are attributes in C#?

Interview Answer

Attributes add metadata to classes, methods, properties, or other code elements.

Example:

[Serializable]

public class Customer

{

}

The attribute provides additional information.


Custom Attribute Example

public class AuditAttribute : Attribute

{

    public string Name { get; }

    public AuditAttribute(string name)

    {

        Name = name;

    }

}

Usage:

[Audit("Customer Creation")]

public void CreateCustomer()

{

}


Common .NET Attributes

Examples:

[HttpGet]

[Authorize]

[Required]

[Obsolete]


48. Explain Dependency Injection lifetimes in .NET.

Interview Answer

ASP.NET Core provides three main dependency injection lifetimes:

  1. Singleton
  2. Scoped
  3. Transient

Singleton

One instance for the entire application lifetime.

Example:

services.AddSingleton<ICache, MemoryCache>();

Use for:


Scoped

One instance per request.

Example:

services.AddScoped<IOrderService, OrderService>();

Common for:

In web applications, one instance per HTTP request.


Transient

A new instance every time it is requested.

Example:

services.AddTransient<IEmailService, EmailService>();

Use for lightweight services.


Comparison

Lifetime

Created

Singleton

Once

Scoped

Once per request

Transient

Every injection


49. What is the difference between Singleton and Scoped?

Interview Answer

Singleton:

Example:

CacheService


Scoped:

Example:

UserContext


Important Interview Point

A singleton should not depend on a scoped service.

Incorrect:

Singleton Service

        |

        |

   Scoped Service

Why?

Because the scoped object lifetime is shorter.

This can cause:


50. What is the Options Pattern in ASP.NET Core?

Interview Answer

The Options Pattern provides strongly typed access to configuration values.

Instead of:

configuration["ConnectionString"]

Use a class.

Example:

public class DatabaseOptions

{

    public string ConnectionString { get; set; }

}

Configuration:

{

  "Database": {

    "ConnectionString": "server=myserver"

  }

}

Register:

services.Configure<DatabaseOptions>(

    configuration.GetSection("Database"));

Use:

public class UserService

{

    private readonly DatabaseOptions options;

    public UserService(

        IOptions<DatabaseOptions> options)

    {

        this.options = options.Value;

    }

}


Benefits


Senior Interview Notes

For senior .NET interviews, remember these key points:

Garbage Collection

Good answer:

"The GC manages managed memory automatically, but developers are responsible for deterministic cleanup of unmanaged resources using IDisposable."


Dependency Injection

Good answer:

"DI reduces coupling by allowing dependencies to be provided externally. It improves testability and maintainability."


Reflection

Good answer:

"Reflection provides runtime type inspection and is heavily used by frameworks, but it should be avoided in performance-critical paths."

51. What is the difference between string and StringBuilder in C#?

Interview Answer

string is immutable, meaning once created it cannot be changed.

Example:

string name = "John";

name = name + " Smith";

A new string object is created. The original string is not modified.


StringBuilder is mutable and allows modifying text without creating many temporary objects.

Example:

StringBuilder builder = new();

builder.Append("John");

builder.Append(" Smith");

string result = builder.ToString();


When to use string?

Use string for:

Example:

var message = "Hello World";


When to use StringBuilder?

Use StringBuilder for:

Example:

StringBuilder report = new();

for(int i = 0; i < 10000; i++)

{

    report.AppendLine($"Line {i}");

}


Senior Answer

String is immutable and optimized for normal usage. StringBuilder reduces allocations when performing many modifications.


52. Why is string immutable in C#?

Interview Answer

Strings are immutable for several reasons:

1. Security

Strings are often used for:

Changing them unexpectedly could create security problems.


2. Thread safety

Multiple threads can safely share the same string object.


3. Performance

The runtime can optimize immutable strings using string interning.

Example:

string a = "hello";

string b = "hello";

The runtime may reuse the same string object.


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

Interview Answer

The behavior depends on the type.


For value types

Both compare values.

Example:

int a = 10;

int b = 10;

Console.WriteLine(a == b);

Result:

True


For reference types

== normally compares references unless overloaded.

Example:

class Person

{

    public string Name {get;set;}

}

var p1 = new Person();

var p2 = new Person();

Console.WriteLine(p1 == p2);

Result:

False

Different objects.


Equals()

Equals() compares logical equality if implemented.

Example:

string a = "hello";

string b = "hello";

Console.WriteLine(a.Equals(b));

Result:

True


Senior Answer

For business objects, I usually override Equals() and GetHashCode() together when value equality is required.


54. What is ReferenceEquals()?

Interview Answer

ReferenceEquals() checks whether two variables point to the exact same object in memory.

Example:

Person p1 = new();

Person p2 = p1;

bool result = ReferenceEquals(p1, p2);

Result:

True

Both references point to the same object.


Example:

Person p1 = new();

Person p2 = new();

ReferenceEquals(p1,p2);

Result:

False


Comparison

Method

Checks

==

Equality operator

Equals()

Logical equality

ReferenceEquals()

Same object reference


55. What are immutable objects?

Interview Answer

An immutable object is an object whose state cannot be changed after creation.

Example:

public record Customer(

    string Name,

    int Age);

After creation:

var customer = new Customer("John",40);

The object cannot be modified directly.


Benefits


Examples in .NET

Immutable types:


56. What is the difference between DateTime and DateTimeOffset?

Interview Answer

DateTime represents date and time but may not contain timezone information.

Example:

DateTime now = DateTime.Now;


DateTimeOffset includes timezone offset.

Example:

DateTimeOffset now = DateTimeOffset.Now;

Example value:

2026-07-25 10:30:00 -04:00


Which should you use?

For enterprise applications:

Prefer:

DateTimeOffset

when working with:


Senior Answer

DateTime can cause ambiguity when applications operate across time zones. DateTimeOffset preserves the actual point in time.


57. What are tuples in C#?

Interview Answer

Tuples allow returning multiple values from a method without creating a custom class.

Example:

public (string Name, int Age) GetUser()

{

    return ("John", 30);

}

Usage:

var user = GetUser();

Console.WriteLine(user.Name);

Console.WriteLine(user.Age);


Before tuples

Developers often created classes:

class UserResult

{

    public string Name;

    public int Age;

}


When to use tuples?

Good for:

Avoid for:


58. What is pattern matching in C#?

Interview Answer

Pattern matching allows checking types and values in a cleaner way.

Example:

object value = 10;

if(value is int number)

{

    Console.WriteLine(number);

}


Switch Pattern Matching

Example:

string GetType(object value)

{

    return value switch

    {

        int => "Integer",

        string => "String",

        null => "Empty",

        _ => "Unknown"

    };

}


Benefits


59. What are switch expressions in C#?

Interview Answer

Switch expressions provide a concise way to return values based on conditions.

Traditional switch:

string result;

switch(status)

{

    case 1:

        result = "Active";

        break;

    case 2:

        result = "Inactive";

        break;

}


Modern switch expression:

string result = status switch

{

    1 => "Active",

    2 => "Inactive",

    _ => "Unknown"

};


Benefits


60. What are some important modern C# features?

Interview Answer

Modern C# versions introduced many productivity improvements.


Records (C# 9)

For immutable data models.

public record Product(

    int Id,

    string Name);


Nullable Reference Types (C# 8)

Helps detect null problems.

string? name;


Pattern Matching

Cleaner conditional logic.

if(customer is PremiumCustomer)

{

}


Top-level Statements

Simplified program entry point.

Before:

class Program

{

    static void Main()

    {

    }

}

After:

Console.WriteLine("Hello");


Global Using Directives

Avoid repeated imports:

global using System;


File-scoped Namespaces

Before:

namespace MyApp

{

    class Program

    {

    }

}

After:

namespace MyApp;

class Program

{

}


Required Properties (C# 11)

Require initialization.

public class User

{

    public required string Name {get;set;}

}


Primary Constructors (C# 12)

Simplify class construction.

public class User(string name)

{

    public string Name => name;

}


Collection Expressions (C# 12)

Simplified collection creation.

int[] numbers = [1,2,3];


Senior Interview Summary

For modern C# interviews, be comfortable explaining:

✅ Value vs reference types
✅ Memory management
✅ OOP principles
✅ Interfaces and abstraction
✅ Delegates and events
✅ LINQ
✅ Async programming
✅ Dependency Injection
✅ Garbage Collection
✅ Records
✅ Nullable reference types
✅ Modern C# features


Chapter 2 — C# Fundamentals Completed ✅