CSharp Interview Guide
CSharp Interview Guide
Contents
C# and .NET Interview Preparation Guide 3
Part 1: .Net Fundamentals & Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Part 2: C# Language Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Part 3: Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Part 4: Advanced C# Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Part 5: Architecture, Patterns & Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Part 6: Entity Framework Core & Modern .Net . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Part 7: Enterprise Scenarios & Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1
Q384. SaveChanges() vs SaveChangesAsync()? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Q385. What is Change Tracking? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Q386. AsNoTracking()? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Q387. Does EF Core support Lazy Loading? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Q388. What is Eager Loading? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Q389. What is Explicit Loading? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Q390. What is the N+1 Problem? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Q391. SplitQuery (.NET 5+)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Q392. Global Query Filters? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Q393. Shadow Properties? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Q394. Concurrency Tokens? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Q395. Migration Bundles (EF Core 6+)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Q396. Raw SQL in EF Core? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Q397. Compile-Time Query ([Link])? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Q398. ExecuteUpdate / ExecuteDelete (EF Core 7)? . . . . . . . . . . . . . . . . . . . . . . . . . 42
Q399. Dapper vs EF Core? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Q400. What are C# 12 Primary Constructors? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Q401. What are Collection Expressions (C# 12)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Q402. What are Interseptors (C# 12)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Q403. What is .NET 8 Keyed Services? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Q404. What is TimeProvider (.NET 8)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Q405. What is FrozenDictionary (.NET 8)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Q406. What is field keyword (C# 13 Preview)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Q407. What is params with Collections (C# 13)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Q408. What is Guid.V7 (C# 13 / .NET 9)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Q409. HybridCache (.NET 9)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Q410. RateLimiting Middleware (.NET 7)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Q411. OutputCaching vs ResponseCaching? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Q412. What is “Vertical Slice Architecture”? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Q413. REPR Pattern? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Q414. Strangler Fig Pattern? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Q415. Sidecar Pattern? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Q416. Ambassador Pattern? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Q417. Backend for Frontend (BFF)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Q418. Idempotency Key? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Q419. Semantic Versioning (SemVer)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Q420. GitFlow vs Trunk Based? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Q421. Feature Flags? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Q422. Blue/Green vs Canary? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Q423. Infrastructure as Code (IaC)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Q424. Structured Logging? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Q425. Correlation ID? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Q426. OpenTelemetry? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Q427. Prometheus vs Grafana? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Q428. ELK Stack? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Q429. Health Checks UI? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Q430. What is a “Post-Mortem”? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Q431. Horizontal vs Vertical Scaling? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Q432. What constitutes a “Senior” Developer? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Q433. Managing Technical Debt? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Q434. Code Review Best Practices? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Q435. How to handle “We need this Yesterday”? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Q436. Explain “You build it, you run it”. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Q437. Service Mesh (Example: Istio/Linkerd)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2
Q438. mTLS (Mutual TLS)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Q439. What is OData? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Q440. WebHook? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3
• Q36. What is the difference between Debug and Release mode?
• Q37. What are Preprocessor Directives (#if, #define)?
• Q38. What is a PDB file?
• Q39. What is NuGet?
• Q40. What is [Link] vs PackageReference?
• Q41. What is the [Link] file?
• Q42. What is [Link]?
• Q43. What is [Link]?
• Q44. What is Environment Variable configuration?
• Q45. What is “User Secrets”?
• Q46. What is the difference between SDK and Runtime?
• Q47. What is “Self-Contained” vs “Framework-Dependent” deployment?
• Q48. What is “Trimming” (IL Linker)?
• Q49. What is “Single File Publish”?
• Q50. What is [Link]?
• Q51. What is “Boxing” and “Unboxing”?
• Q52. What is [Link] immutability?
• Q53. What is String vs string?
• Q54. What is String Interpolation ($)?
• Q55. What is a Verbatim String (@)?
• Q56. What is a Raw String Literal (""")? (C# 11)
• Q57. What is typeof vs GetType()?
• Q58. What is the difference between const and readonly?
• Q59. What is static class?
• Q60. Difference between Value Types and Reference Types?
4
• Q87. What are “Named Arguments”?
• Q88. What are “Optional Parameters”?
• Q89. What is a “Local Function”?
• Q90. Local Function vs Lambda?
• Q91. What is a Tuple?
• Q92. What is Deconstruction?
• Q93. What is Pattern Matching?
• Q94. What is the discard variable (_)?
• Q95. What is Recursion?
• Q96. What is Tail Recursion?
• Q97. What is an Iterator Method?
• Q98. What is yield return?
• Q99. What is yield break?
• Q100. Limitations of yield?
• Q101. What is an Indexer?
• Q102. What is Operator Overloading?
• Q103. What is User-Defined Conversion?
• Q104. What is a Delegate?
• Q105. What is Action vs Func?
• Q106. What is a Predicate?
• Q107. What is an Anonymous Method?
• Q108. What is a Lambda Expression?
• Q109. What is Closure?
• Q110. What is Expression Tree?
• Q111. What is Reflection?
• Q112. What is Dynamic Loading?
• Q113. What is [Link]?
• Q114. What are Generic Attributes (C# 11)?
• Q115. What are Caller Information Attributes?
• Q116. What is the dynamic keyword really?
• Q117. dynamic vs Reflection?
• Q118. What is ExpandoObject?
• Q119. What is unsafe code?
• Q120. What is fixed statement?
5
• Q138. Constructor Chaining?
• Q139. What is a Destructor (Finalizer)?
• Q140. Access Modifiers: public vs internal?
• Q141. Access Modifiers: protected vs private?
• Q142. What is protected internal?
• Q143. What is private protected (C# 7.2)?
• Q144. What are Properties vs Fields?
• Q145. What are Auto-Implemented Properties?
• Q146. What is init accessor (C# 9)?
• Q147. What are Required Properties (C# 11)?
• Q148. What is an Indexer?
• Q149. What is Object Initializer Syntax?
• Q150. Copy Constructor?
• Q151. Shallow Copy vs Deep Copy?
• Q152. What is Method Overloading?
• Q153. What is Operator Overloading?
• Q154. What is [Link] methods?
• Q155. Why override ToString()?
• Q156. Why override Equals()?
• Q157. Contract between Equals and GetHashCode?
• Q158. What is IEquatable<T>?
• Q159. What is IComparable<T>?
• Q160. What is Cohesion?
• Q161. What is Coupling?
• Q162. Dependency Injection (DI) basics?
• Q163. Composition over Inheritance?
• Q164. What is a “Mixin” (via Interface)?
• Q165. Extension Methods?
• Q166. Can Extension Methods access private fields?
• Q167. What are Records (C# 9)?
• Q168. record class vs record struct?
• Q169. What is with expression?
• Q170. Anonymous Types?
• Q171. What is dynamic dispatch?
• Q172. Covariance vs Contravariance?
• Q173. Where is Covariance used?
• Q174. What is the Diamond Problem?
• Q175. What is a Nested Class?
• Q176. Flags Enum attribute?
• Q177. Null Object Pattern?
• Q178. What is the “God Object” anti-pattern?
• Q179. Immutable Object benefits?
• Q180. How to make a class immutable?
• Q181. SOLID: S - Single Responsibility?
• Q182. SOLID: O - Open/Closed?
• Q183. SOLID: L - Liskov Substitution?
• Q184. SOLID: I - Interface Segregation?
• Q185. SOLID: D - Dependency Inversion?
6
• Q204. Array vs List<T>?
• Q205. How does List<T> grow?
• Q206. Dictionary<K,V> internal working?
• Q207. HashSet<T> vs List<T>?
• Q208. Queue<T> vs Stack<T>?
• Q209. LinkedList<T>?
• Q210. ConcurrentDictionary<K,V>?
• Q211. BlockingCollection<T>?
• Q212. What is LINQ?
• Q213. Deferred Execution?
• Q214. IQueryable vs IEnumerable?
• Q215. Select vs SelectMany?
• Q216. GroupBy in LINQ?
• Q217. First vs FirstOrDefault?
• Q218. Single vs SingleOrDefault?
• Q219. Join vs GroupJoin?
• Q220. Zip operator?
• Q221. What is an Event?
• Q222. EventHandler<T>?
• Q223. Memory Leak with Events?
• Q224. What are Exception Filters (when)?
• Q225. throw vs throw ex?
• Q226. What is AggregateException?
• Q227. Custom Exceptions?
• Q228. Garbage Collection (GC) Basics?
• Q229. GC Generations (0, 1, 2)?
• Q230. Large Object Heap (LOH)?
• Q231. IDisposable pattern?
• Q232. Finalizer (~Class) vs Default GC?
• Q233. using statement and IDisposable?
• Q234. Weak Reference?
• Q235. What is GCHandle?
• Q236. StackOverflowException?
• Q237. OutOfMemoryException?
• Q238. Reflection Performance?
• Q239. Attributes vs Interfaces?
• Q240. Func<T> vs Expression Tree?
• Q241. Covariance in Generics?
• Q242. Contravariance in Generics?
• Q243. Extension method priority?
• Q244. Nullable Reference Types (string?)?
• Q245. Null-Forgiving operator (!)?
• Q246. Memory<T> vs Span<T>?
• Q247. ArrayPool<T>?
• Q248. stackalloc?
• Q249. [Link] vs Newtonsoft?
• Q250. Source Generators?
• Q251. What is Dynamic Language Runtime (DLR)?
• Q252. Volatile Keyword?
• Q253. Interlocked class?
• Q254. Monitor class?
• Q255. AutoResetEvent vs ManualResetEvent?
• Q256. Mutex vs Semaphore?
• Q257. ThreadPool?
7
• Q258. Task vs Thread?
• Q259. [Link] vs [Link]?
• Q260. Context Switching?
• Q261. Async/Await State Machine?
• Q262. ConfigureAwait(false)?
• Q263. [Link] vs [Link]?
• Q264. ValueTask<T>?
• Q265. IAsyncEnumerable<T> (Async Streams)?
• Q266. Channel<T>?
• Q267. Deadlock common cause?
• Q268. Race Condition?
• Q269. CancellationToken?
• Q270. [Link] vs [Link]?
• Q271. ConcurrentBag vs ConcurrentQueue?
• Q272. Thread Local Storage (ThreadLocal<T>)?
• Q273. AsyncLocal<T>?
• Q274. Atomic Operation?
• Q275. Lock-free programming?
• Q276. Starvation (Threading)?
• Q277. False Sharing?
• Q278. Memory Barrier?
• Q279. SpinLock?
• Q280. What is PLINQ?
8
• Q309. What is Idempotency?
• Q310. What is a Saga?
• Q311. SOLID: Single Responsibility Principle (SRP)?
• Q312. SOLID: Open/Closed Principle (OCP)?
• Q313. SOLID: Liskov Substitution Principle (LSP)?
• Q314. SOLID: Interface Segregation Principle (ISP)?
• Q315. SOLID: Dependency Inversion Principle (DIP)?
• Q316. DRY (Don’t Repeat Yourself)?
• Q317. YAGNI (You Ain’t Gonna Need It)?
• Q318. KISS (Keep It Simple, Stupid)?
• Q319. What is Unit Testing?
• Q320. What is Integration Testing?
• Q321. What is E2E (End to End) Testing?
• Q322. Stub vs Mock?
• Q323. AAA Pattern?
• Q324. Code Coverage?
• Q325. TDD (Test Driven Development)?
• Q326. xUnit vs NUnit/MSTest?
• Q327. IClassFixture in xUnit?
• Q328. Theory and InlineData?
• Q329. Test Pyramid?
• Q330. What is “Flaky Test”?
• Q331. What is REST?
• Q332. HTTP Verbs (GET, POST, PUT, PATCH, DELETE)?
• Q333. HTTP Status Codes?
• Q334. SOAP vs REST?
• Q335. What is GraphQL?
• Q336. gRPC?
• Q337. API Gateway?
• Q338. Authentication vs Authorization?
• Q339. JWT (JSON Web Token)?
• Q340. OAuth2 vs OpenID Connect (OIDC)?
• Q341. CORS (Cross-Origin Resource Sharing)?
• Q342. HATEOAS?
• Q343. What is Middleware in [Link] Core?
• Q344. IApplicationBuilder?
• Q345. IServiceCollection?
• Q346. Minimal APIs (C# 10)?
• Q347. Model Binding?
• Q348. Model Validation?
• Q349. Filters in [Link] Core?
• Q350. SignalR?
• Q351. Razor Pages?
• Q352. Blazor?
• Q353. Kestrel?
• Q354. Reverse Proxy?
• Q355. What is the “Host” (Generic Host)?
• Q356. BackgroundService / HostedService?
• Q357. Swagger / OpenAPI?
• Q358. Health Checks?
• Q359. Rate Limiting?
• Q360. Response Caching?
• Q361. Output Caching (New .NET 7+)?
• Q362. Distributed Caching?
9
• Q363. Sticky Sessions?
• Q364. Anti-Forgery Token (CSRF)?
• Q365. XSS (Cross Site Scripting)?
• Q366. SQL Injection?
• Q367. Open Redirect Vulnerability?
• Q368. Data Protection API (DPAPI)?
• Q369. Secret Management?
• Q370. HTTPS / SSL?
• Q371. What is Docker?
• Q372. Image vs Container?
• Q373. Dockerfile?
• Q374. Docker Compose?
• Q375. Kubernetes (K8s)?
• Q376. Microservices Communication styles?
• Q377. Eventual Consistency?
• Q378. Distributed Tracing?
• Q379. Blue/Green Deployment?
• Q380. Canary Deployment?
10
• Q414. Strangler Fig Pattern?
• Q415. Sidecar Pattern?
• Q416. Ambassador Pattern?
• Q417. Backend for Frontend (BFF)?
• Q418. Idempotency Key?
• Q419. Semantic Versioning (SemVer)?
• Q420. GitFlow vs Trunk Based?
• Q421. Feature Flags?
• Q422. Blue/Green vs Canary?
• Q423. Infrastructure as Code (IaC)?
• Q424. Structured Logging?
• Q425. Correlation ID?
• Q426. OpenTelemetry?
• Q427. Prometheus vs Grafana?
• Q428. ELK Stack?
• Q429. Health Checks UI?
• Q430. What is a “Post-Mortem”?
• Q431. Horizontal vs Vertical Scaling?
• Q432. What constitutes a “Senior” Developer?
• Q433. Managing Technical Debt?
• Q434. Code Review Best Practices?
• Q435. How to handle “We need this Yesterday”?
• Q436. Explain “You build it, you run it”.
• Q437. Service Mesh (Example: Istio/Linkerd)?
• Q438. mTLS (Mutual TLS)?
• Q439. What is OData?
• Q440. WebHook?
11
• Q464. Mentoring Juniors?
• Q465. Handling Conflict with Product Owner?
• Q466. Production Outage Protocol?
• Q467. “It works on my machine”?
• Q468. Bus Factor?
• Q469. Trunk-Based Development?
• Q470. Database Migration Strategy?
• Q471. Distributed ID Generation?
• Q472. Blob Storage vs Database?
• Q473. CDN (Content Delivery Network)?
• Q474. WebSockets vs Server-Sent Events (SSE)?
• Q475. Serialization: Private setters?
• Q476. Value Objects (DDD)?
• Q477. Aggregate Root (DDD)?
• Q478. Anemic Domain Model (Anti-pattern)?
• Q479. Hexagonal Architecture?
• Q480. Event Storming?
• Q481. Competing Consumers Pattern?
• Q482. Leaky Bucket Algorithm?
• Q483. Thundering Herd Problem?
• Q484. Poison Message?
• Q485. Polyglot Persistence?
• Q486. Function as a Service (Serverless)?
• Q487. Cold Start?
• Q488. What is IOptions<T>?
• Q489. [Link] Use Case?
• Q490. Why prefer DateTimeOffset over DateTime?
• Q491. IEnumerable vs IReadOnlyList for API Returns?
• Q492. How to secure a Microservice?
• Q493. Side-Effect in GET request?
• Q494. Richardson Maturity Model?
• Q495. Grpc-Web?
• Q496. When to use SignalR?
• Q497. What is Blazor Server trade-off?
• Q498. What is Blazor WASM trade-off?
• Q499. Resume-Driven Development?
• Q500. Final Question: How do you stay current?
Q1. What is the difference between .NET Framework, .NET Core, and .NET
(5/6/7/8)?
Short Answer: .NET Framework is the legacy, Windows-only runtime. .NET Core was the open-source,
cross-platform rewrite. .NET 5+ is the unified successor that merges the best of both.
Detailed Explanation:
1. .NET Framework (2002-2019):
• Architecture: Windows-only, system-wide installation (GAC).
• Components: Heavily relied on IIS ([Link]), WCF, and AppDomains.
• Status: Version 4.8 is the final version. Supported but in maintenance mode.
12
• Use Case: Legacy enterprise monoliths (WMS/OMS) that depend on Windows-specific APIs.
2. .NET Core (2016-2019):
• Architecture: Cross-platform (Windows, Linux, macOS), side-by-side deployment (no GAC),
lightweight.
• Components: Modular (NuGet packets). Removed [Link], WCF Server, and AppDomains.
• Status: EOL (End of Life). Replaced by .NET 5+.
3. .NET (5/6/7/8/9):
• Unified Platform: Dropped “Core” from the name. It unifies Desktop (WPF/WinForms), Web,
Cloud, Mobile (MAUI), and IoT.
• Performance: Massive JIT improvements, AOT compilation, and low-allocation APIs (Span).
• Current Standard: .NET 8 (LTS) is the current standard for all new development.
Architectural implication: Migrating from Framework to .NET 8 is not just a “version upgrade”; it’s
a re-platforming. You move from IIS/AppDomains to Kestrel/Containers. *** ## Q2. What is .NET
Standard and why is it (mostly) irrelevant now?
Short Answer: .NET Standard was a formal specification of APIs that different .NET runtimes (Framework,
Core, Mono) had to implement to ensure code sharing. It solved the fragmentation problem.
Detailed Explanation:
• The Problem: Before .NET Standard, sharing code between a Xamarin mobile app, a .NET Framework
WCF service, and a .NET Core Web API was difficult because they supported different API sets
(PCLs).
• The Solution: .NET Standard defined a common logical interface. If a library targeted .NET Standard
2.0, it could run on any runtime that implemented Standard 2.0.
• Current State: With the unification of .NET 5+, .NET Standard is largely obsolete for new code. You
should target net8.0 directly. However, if you write a library that MUST support legacy Framework
apps and modern .NET apps, you still target .NET Standard 2.0 as the “lowest common denominator”.
Key Takeaway: Target net8.0 for applications. Target netstandard2.0 for shared libraries widely
consumed by legacy systems. *** ## Q3. What is the GAC (Global Assembly Cache) and why was it
removed in .NET Core?
Short Answer: The GAC was a central Windows folder to store shared .NET assemblies. It was removed
in .NET Core to solve “DLL Hell” and enable side-by-side deployments.
Detailed Explanation:
The GAC (Legacy): * Located at C:\Windows\[Link]\assembly. * Allowed multiple apps to
share one DLL (e.g., [Link]) to save disk space. * The FLaw (DLL Hell): If an update to
a shared DLL in the GAC broke backward compatibility, every application on the server using that DLL
would crash. It made deployments risky and tightly coupled.
The Modern Approach (.NET Core+): * App-Local Dependencies: Every application carries its
own private copy of all required DLLs in its own folder. * Self-Contained Deployment: You can even
bundle the .NET Runtime itself with your app. * Benefit: Two apps on the same server can use different
versions of the same library without conflict. This is essential for Microservices and Containerization rules.
*** ## Q4. What are AppDomains and why doesn’t .NET Core support them?
Short Answer: AppDomains provided lightweight isolation within a single process in .NET Framework.
They were expensive to implement and complex. .NET Core replaced them with Containers (process-level
isolation) and AssemblyLoadContext (loading/unloading assemblies).
Detailed Explanation:
Legacy Use Case: In IIS, many websites ran inside one [Link] worker process. AppDomains isolated
them so if one site crashed, it didn’t take down the others. They were also used for plugins that could be
“unloaded” to free memory.
13
Modern Replacement: 1. Isolation -> Containers (Docker): Instead of virtual isolation in-
side a process, we use OS-level isolation via containers. Each service gets its own lightweight environ-
ment. 2. Unloading -> AssemblyLoadContext (ALC): For plugin systems where you need to
load/unload DLLs dynamically (e.g., a WMS loading a specific carrier adapter), .NET Core provides
[Link]. This allows unloading assemblies without killing the pro-
cess, but it’s much harder to use correctly than AppDomains. *** ## Q5. What is the Common Language
Runtime (CLR)?
Short Answer: The CLR is the execution engine for .NET. It handles the lifecycle of the application:
memory management (GC), thread execution, code safety verification, JIT compilation, and exception
handling.
Detailed Explanation:
When you run a .NET application, the OS starts the CLR, which creates a Managed Environment. Its
key responsibilities are: 1. JIT Compilation: Converts Intermediate Language (MSIL) to Native Machine
Code. 2. Memory Management: Allocates objects on the Heap and runs Garbage Collection (GC) to
reclaim memory. 3. Type Safety: Ensures you don’t perform invalid operations (like accessing an array
index out of bounds or casting incompatible types). 4. Exception Handling: Provides a unified way to
handle runtime errors across languages (C#, F#, VB). 5. Thread Management: Maps managed Threads
to OS Threads and manages the Thread Pool.
Analogy: The CLR is the “Virtual Machine” for .NET, similar to the JVM for Java. *** ## Q6. What is
JIT (Just-In-Time) Compilation?
Short Answer: JIT is the process where the CLR translates MSIL (bytecode) into Native Machine Code at
runtime, just before the method is executed for the first time.
Detailed Explanation:
The Execution Flow: 1. Source Code (C#): Compiled by Roslyn into MSIL (DLL/EXE). 2. Load
Time: When the app starts, the CLR loads the MSIL. 3. Runtime (JIT): When a method is called: *
The JIT compiler reads the MSIL for that method. * It optimizes it for the specific CPU (e.g., using AVX
instructions if available). * It generates native machine code stored in memory. * Subsequent calls run the
native code directly (near C++ speed).
Types of JIT: * Standard JIT: Compiles method-by-method on demand. Has a slight “Warm-up” cost. *
Tiered Compilation: (Default in .NET 8) Starts with a “Quick JIT” (lower optimization, fast startup)
and re-compiles frequently used “Hot” methods with “Full Optimization” in the background. * PGO
(Profile-Guided Optimization): The JIT learns from actual runtime behavior to optimize code paths even
further (e.g., devirtualizing method calls). *** ## Q7. What consists of the .NET Ecosystem? (Visualizing
the stack)
Short Answer: The ecosystem consists of: Languages (C#, F#), Runtime (CLR), Libraries (Base Class
Library), SDK (CLI tools), and App Models ([Link] Core, MAUI).
Detailed Explanation:
1. Languages: C# (OOP), F# (Functional), [Link] (Legacy).
2. Compiler: Roslyn (C# compiler as a service).
3. Runtime: CoreCLR (The execution engine).
4. Base Class Library (BCL): The massive set of built-in APIs (System.*, [Link],
[Link], [Link]).
5. App Models: Frameworks built on top of the BCL:
• [Link] Core: Web APIs, Blazor.
• MAUI: Cross-platform mobile/desktop.
• WPF/WinForms: Windows UI.
• Entity Framework Core: Data Access.
14
Interview Note: Senior devs understand that [Link] comes from the BCL, but HttpContext
comes from the App Model ([Link] Core). They are separate layers. *** ## Q8. What is MSIL (Microsoft
Intermediate Language) and why is it important?
Short Answer: MSIL (or IL) is a CPU-independent instruction set. C# compiles to IL, not machine code.
This allows “Write Once, Run Anywhere” (portability) and Language Interoperability.
Detailed Explanation:
Why not compile to native code directly? 1. Portability: The same DLL can run on x64 Windows,
ARM64 Linux, or Apple Silicon M2 because the IL is agnostic. The CLR on that specific machine handles
the final translation (JIT). 2. Interoperability: Since C#, F#, and [Link] all compile to the same IL,
they can easily call each other’s libraries. 3. Metadata: IL contains rich metadata about types, members,
and references, enabling powerful features like Reflection.
Example: C# int a = 10; becomes IL ldc.i4.s 10. *** ## Q9. Explain Managed vs. Unmanaged
Code.
Short Answer: Managed Code executes under the control of the CLR (GC, Safety). Unmanaged Code
executes directly on the OS (C++, Win32 APIs) with manual memory management.
Detailed Explanation:
Managed Code: * Environment: Runs inside CLR. * Benefits: Automatic memory cleanup (GC), Type
Safety, Array bounds checking. * Examples: C#, [Link], F#.
Unmanaged Code: * Environment: Runs directly on OS. * Characteristics: Developer accesses memory
pointers directly. Must manually malloc/free memory. * Risks: Memory leaks, Buffer overflows, Access
Violations (Segfaults). * Interop: .NET calls unmanaged code via P/Invoke (Platform Invoke) or COM
Interop.
WMS Scenario: Calling a legacy Barcode Scanner Driver (written in C) from your C# service involves
crossing the Managed/Unmanaged boundary. This “Marshaling” of data costs performance and requires
careful failure handling. *** ## Q10. What is Stack vs Header memory in .NET?
Short Answer: Stack is small, fast, LIFO memory for method execution (Value Types). Heap is large,
slower memory for long-lived objects (Reference Types) managed by the GC.
Detailed Explanation: (See Q60+ for deep dive on Value/Reference types)
The Stack: * Stores: Value Types (int, bool, struct) declared in methods, and Pointer references to
heap objects. * Lifecycle: Automatically cleaned up when the method returns (pops off stack). * Speed:
Extremely fast (CPU cache friendly). * Limit: Small (usually 1MB per thread). StackOverflowException
occurs if exceeded.
The Heap: * Stores: Reference Types (class, string, array, delegate, interface). * Lifecycle: Managed
by Garbage Collector. Objects persist until no longer referenced. * Speed: Slower allocation/access than
Stack. * Structure: Divided into Generations (0, 1, 2) and LOH (Large Object Heap). *** ## Q11. What is
the CTS (Common Type System)?
Short Answer: CTS is a standard that defines how data types are declared, used, and managed in the
runtime. It ensures that an int in C# and an Integer in [Link] are bit-level identical (System.Int32).
Value for Interview: It explains how .NET languages can talk to each other. Without CTS, you would
need complex data conversion layers between a C# library and an F# consumer. CTS guarantees type
compatibility at the binary level. *** ## Q12. What is the CLS (Common Language Specification)?
Short Answer: CLS is a subset of CTS rules that strict interoperability requires. It defines the “lowest
common denominator” features that all .NET languages must support.
Scenario: C# supports unsigned integers (uint), but some older .NET languages did not. To be “CLS-
Compliant” (usable by any .NET language), a public library method should not return uint. Attribute:
15
[assembly: CLSCompliant(true)] checks this for you. *** ## Q13. What is an Assembly in .NET?
Short Answer: An Assembly is the fundamental unit of deployment, versioning, and security in .NET. It is
generally a compiled .dll (library) or .exe (executable).
Contents of an Assembly: 1. MSIL Code: The logic. 2. Metadata: Description of specific types,
methods, and attributes defined in the code. 3. Manifest: “The ID Card” - contains version [Link],
Culture, Public Key Token (for signing), and huge list of dependencies. *** ## Q14. What is the difference
between an EXE and a DLL?
Short Answer: Technically both are assemblies with the same PE (Portable Executable) structure. The
only difference is the entry point. * EXE: Has an entry point (Main method) and can be executed by the OS.
* DLL: Library with no entry point. Must be hosted/called by an EXE.
Modern .NET Note: In .NET Core, even “Executables” are often [Link] which is run by a generic driver
dotnet [Link]. *** ## Q15. What are the major breaking changes from .NET Framework to .NET Core?
Key Checkpoint for Migration Projects: 1. No [Link]: The heavy IIS coupling is gone.
Replaced by [Link].* middleware pipeline. 2. Configuration: [Link] (XML) is
replaced by [Link] and Environment Variables. 3. No WCF Server: You cannot host WCF
services easily in Core (use gRPC or CoreWCF community port). 4. No AppDomains: Re-architect using
Containers. 5. Reflection API: Changed significantly to be more lightweight (TypeInfo vs Type). *** ##
Q16. What is “Native AOT” introduced in .NET 7/8?
Short Answer: Native AOT (Ahead-of-Time) compiles C# directly to standalone machine code at build
time, skipping the IL step and removing the need for a JIT compiler at runtime.
Benefits: * Startup Time: Instant (no JIT warm-up). * Size: Smaller distribution (no full CLR needed).
* Security: harder to reverse engineer (no IL to decompile).
Trade-offs: * No dynamic code generation ([Link]). * Restricted Reflection capabilities. * Required
for environments that ban JIT (e.g., some consoles, iOS). *** ## Q17. What is CoreCLR vs. CoreRT?
• CoreCLR: The standard runtime used by .NET Core/.NET 5+. Uses JIT. The default for 99% of
web apps.
• CoreRT (now Native AOT): The experimental runtime for AOT compilation. Now integrated as
the NativeAOT publishing mode. *** ## Q18. What is the “Dotnet CLI” and why use it over Visual
Studio?
Short Answer: The CLI (dotnet command) is the cross-platform toolchain for building, testing, and
publishing .NET apps.
Why it matters: * CI/CD Automation: Jenkins/GitHub Actions don’t have a GUI. They run dotnet
build. * Cross-Platform: Works the same on Mac/Linux where Visual Studio (Full) isn’t available. *
Scriptability: Easier to write setup scripts than clicking VS menus.
Common Commands: * dotnet new webapi * dotnet restore * dotnet build * dotnet test * dotnet
publish -c Release *** ## Q19. What is “Roslyn”?
Short Answer: Roslyn is the .NET Compiler Platform. It treats “Compilation as a Service.”
Old World: Compiler was a black box. Source In -> EXE Out. Roslyn World: Compiler is an API. You
can write code that analyzes other code. Use Cases: 1. Refactoring tools: (Rename, Extract Method). 2.
Analyzers: (StyleCop, SonarQube rules). 3. Source Generators: Generating code during compilation
(e.g., [Link] source generator). *** ## Q20. What is a “Solution” (.sln) vs “Project” (.csproj)?
• Project (.csproj): A logical unit of code that compiles to a single assembly (DLL/EXE). Contains
source files and NuGet references.
• Solution (.sln): A container for managing multiple related projects. It defines build dependencies
(Project A depends on Project B) and build configurations. *** ## Q21. Explain the “Main” method
in C#.
16
Short Answer: static void Main(string[] args) is the convention-based Entry Point where execution
begins.
Modern Variations: * Top-Level Statements (C# 9): You can omit the Main method and class
wrapper entirely for simple console apps. The compiler generates the Main boilerplate for you. * Async
Main: static async Task Main() allows using await immediately on startup. *** ## Q22. What are
“Top-Level Statements”?
Short Answer: A C# 9 feature that removes the need for Program class and Main method boilerplate.
Code:
// Before
class Program { static void Main() { [Link]("Hi"); } }
// After (Top-Level)
[Link]("Hi");
Restriction: Only one file in the project can use Top-Level statements. *** ## Q23. What is the difference
between var and dynamic?
Short Answer: var is static typing (compile-time). dynamic is dynamic typing (runtime).
Detailed Explanation: * var: Syntactic sugar. Compiler infers the type. var i = 10; compiles to int i
= 10;. It is strictly typed, safe, and performant. * dynamic: Bypasses compile-time checking. dynamic d
= 10; [Link](); compiles fine but crashes at runtime. It uses reflection/DLR under the hood and
has performance overhead. * Usage: Use var everywhere. Use dynamic only when talking to COM, Python,
or JSON with unknown schemas. *** ## Q24. What is strict type safety?
Short Answer: Strict type safety means the compiler enforces that variable types matches the data they
hold. You cannot assign a string to an integer variable. This eliminates a whole class of “Type Mismatch”
bugs common in JavaScript. *** ## Q25. What is the using statement (Resource Management)?
Short Answer: It acts as a try-finally block to ensure IDisposable objects are disposed (cleaned up)
correctly, even if an exception occurs.
Syntax Evolution:
// Old
using (var file = [Link]("[Link]")) {
[Link]("Data");
}
17
indentation waste. csharp namespace [Link]; // Applies to whole file public
class Order { } *** ## Q28. What are Attributes ([...]) in C#?
Short Answer: Attributes add “Metadata” to code elements (classes, methods, props). They don’t change
logic directly but are read by tools/runtime via Reflection to alter behavior.
Examples: * [Obsolete]: Compiler warns if used. * [Serializable]: Tells serializers to process this
class. * [HttpPost]: Tells [Link] Core this method handles POST requests. *** ## Q29. What is XML
Documentation comments (///)?
Short Answer: Special comments starting with /// that the compiler processes to generate API documen-
tation (IntelliSense tooltips).
Best Practice: Always document public APIs (Summary, Params, Returns, Exceptions).
/// <summary>
/// Calculates tax for an order.
/// </summary>
/// <param name="amount">The net total. </param>
/// <returns>Tax amount. </returns>
public decimal CalculateTax(decimal amount) { ... }
Process(order);
18
Q33. What is “Fail Fast” principle?
Short Answer: If the system enters an invalid state (e.g., null config, missing DB connection), crash
immediately with a clear error. Why? Continuing with invalid state leads to data corruption, which is much
harder to debug than a crash log. *** ## Q34. What is “Single Responsibility Principle” (SRP) in methods?
Short Answer: A method should do one thing. * Bad: ProcessOrder that validates input, calculates
tax, saves to DB, and sends email. * Good: ProcessOrder orchestrates calls to Validator, TaxService,
Repository, and EmailSender. Rule of Thumb: If a method is > 30 lines, it’s likely violating SRP. ***
## Q35. What is region directive and should you use it?
Short Answer: #region allows folding code blocks in the editor. Controversial: Many seniors advise
against using regions to hide massive methods. If you need regions to make a file readable, the class is likely
too big (God Class) and should be refactored. Use regions sparingly for grouping Interface implementations
or Boilerplate. *** ## Q36. What is the difference between Debug and Release mode?
Short Answer: * Debug: No optimization. Contains full debug symbols (PDBs). Easier to step through.
Slower. * Release: Compiler optimizations enabled (inlining, dead code removal). Faster. Harder to debug
(lines verify). Deployment target. *** ## Q37. What are Preprocessor Directives (#if, #define)?
Short Answer: Commands to the compiler to include/exclude code based on build symbols.
Use Case:
#if DEBUG
[Link]("Debug Trace: " + data);
#endif
This line won’t even exist in the Release DLL. *** ## Q38. What is a PDB file?
Short Answer: Program Database file. It maps the compiled binary (MSIL) back to the original source code
lines. Critical: You need PDBs to get line numbers in Exception Stack Traces. In .NET Core, “Portable
PDBs” are cross-platform. *** ## Q39. What is NuGet?
Short Answer: The package manager for .NET. (Like NPM for JS, Maven for Java). It manages dependencies,
versions, and restores libraries from central repositories ([Link]) or private feeds (Azure Artifacts). ***
## Q40. What is [Link] vs PackageReference?
• [Link]: Old (Legacy Framework). XML file listing packages. Packages stored in a local
“packages” folder.
• PackageReference: Modern (.NET Core / SDK Style). Dependencies listed directly in .csproj.
Packages stored in global user cache (saves disk space). Logic is transitive (A depends on B, you get B
automatically). *** ## Q41. What is the [Link] file?
Short Answer: It defines which version of the .NET SDK should be used to build the project. Why:
Ensures the whole team uses exactly usage SDK 8.0.100 regardless of what latest version they have installed.
*** ## Q42. What is [Link]?
Short Answer: Configures the local development environment (VS/CLI). Defines profiles (IIS Express,
Kestrel), Environment variables (ASPNETCORE_ENVIRONMENT=Development), and ports. Note: NOT used in
Production. *** ## Q43. What is [Link]?
Short Answer: The runtime configuration file for .NET Core apps. Replaces [Link] appSettings.
Supports hierarchy ([Link] overrides [Link]) and complex Types
(JSON objects), not just key-value strings. *** ## Q44. What is Environment Variable configuration?
Short Answer: Configuration paradigm for Cloud/Containers. Settings are read from the OS environment
variables (e.g., ConnectionStrings__Default). Security: Secrets (DB Passwords) should effectively use
Environment Variables (injected by K8s or Azure KeyVault), NEVER stored in [Link] committed
to Git. *** ## Q45. What is “User Secrets”?
19
Short Answer: A tool for local development to store sensitive config (passwords) outside the project folder.
Prevents accidental git commits of credentials. *** ## Q46. What is the difference between SDK and
Runtime?
• SDK (Software Development Kit): Includes everything needed to build apps: Compiler (Roslyn),
MSBuild, CLI tools, AND the Runtime. (For Developers/CI Servers).
• Runtime: Includes only what’s needed to run apps. Smaller. (For Production Servers). *** ## Q47.
What is “Self-Contained” vs “Framework-Dependent” deployment?
• Framework-Dependent: Small app size. requires .NET Runtime installed on the target machine.
• Self-Contained: Huge app size. Bundles the .NET Runtime with the app. Runs on a pristine machine
with zero pre-reqs. Good for shipping tools or Microservices in minimal containers (“Distroless”). ***
## Q48. What is “Trimming” (IL Linker)?
Short Answer: Used with Self-Contained deployments. The compiler analyzes code and removes unused
classes/methods from the framework libraries to reduce app size. Risk: Can break Reflection-heavy code
that looks for types dynamically. *** ## Q49. What is “Single File Publish”?
Short Answer: Bundles the app and all its DLL dependencies into one single .exe file. Simplifies distribution.
Internal: It (usually) extracts files to a temp folder to run or loads them directly from memory bundle. ***
## Q50. What is [Link]?
Short Answer: The base class of ALL types in .NET (Value types and Reference types). Methods:
ToString(), Equals(), GetHashCode(), GetType(). *** ## Q51. What is “Boxing” and “Unboxing”?
Short Answer: * Boxing: Converting a Value Type (stack) to object (heap). Expensive (allocation).
* Unboxing: Converting object back to Value Type. Expensive (type check). * Goal: AVOID IT. Use
Generics (List<int>) instead of ArrayList. *** ## Q52. What is [Link] immutability?
Short Answer: Strings in C# are immutable. Once created, they cannot be changed. Modifying a string
creates a new string object. Performance: Use StringBuilder for heavy manipulation loops to avoid
creating thousands of garbage string objects. *** ## Q53. What is String vs string?
Short Answer: * string: C# keyword (alias). * [Link]: The CLR type. * Functionally:
Identical. * Convention: Use string for variables (string name), uses String for static method calls
([Link]). *** ## Q54. What is String Interpolation ($)?
Short Answer: Modern syntax to format strings. $"Hello {name}" is compiled into [Link]("Hello
{0}", name). Efficiency: In .NET 6+, it compiles to highly optimized DefaultInterpolatedStringHandler
(zero allocation if done right). *** ## Q55. What is a Verbatim String (@)?
Short Answer: Disables escape characters. @"C:\Folder\[Link]". Good for regex and paths. Can span
multiple lines. *** ## Q56. What is a Raw String Literal (""")? (C# 11)
Short Answer: Allows multi-line strings containing quotes without escaping.
var json = """
{ "name": "John" }
""";
Eliminates “Leaning toothpick syndrome” (\") in JSON/SQL strings. *** ## Q57. What is typeof vs
GetType()?
• typeof(int): Compile-time operator. Used when you know the type name.
• [Link](): Runtime method. Used when you have an instance and need its exact runtime type.
*** ## Q58. What is the difference between const and readonly?
• const: Compile-time constant. Value substituted at usage site. Must be initialized at declaration.
• readonly: Runtime constant. Can be set in Constructor.
20
• Versioning Trap: If you update a const value in a DLL but don’t recompile the consuming App, the
App still uses the old value (burned in). Use readonly or properties for public libraries. *** ## Q59.
What is static class?
Short Answer: A class that cannot be instantiated and contains only static members. Usage: Utility
functions (Math), Extension Methods helper classes. Design: It’s sealed and abstract implicitly. *** ##
Q60. Difference between Value Types and Reference Types?
Short Answer: * Value Types (struct, enum, int, bool): Hold data directly. Assignment copies data.
Usually live on Stack. * Reference Types (class, interface, string, array): Hold pointer to memory
address. Assignment copies pointer (two vars point to same object). Live on Heap. * End of Part 1**
21
Best Practice: Always use TryParse when processing user input to avoid exceptions (Flow Control via
Exceptions is bad). *** ## Q66. What is the as operator?
Short Answer: Performs a safe cast for Reference Types. * Success: Returns the object cast to type. *
Failure: Returns null (instead of throwing InvalidCastException).
Example:
object obj = "Hello";
string s = obj as string; // "Hello"
Order o = obj as Order; // null
22
Short Answer: Returns the string name of a variable, type, or member. if (arg == null) throw new
ArgumentNullException(nameof(arg)); Benefit: Refactoring-safe. If you rename arg to input, the string
updates automatically. *** ## Q74. What are Bitwise Operators (<<, >>, &, |)?
Short Answer: Operate on individual bits. * << (Left Shift): Multiply by 2. * >> (Right Shift): Divide
by 2. * & (AND), | (OR): Used for masking flags. *** ## Q75. What is the difference between Switch
Statement and Switch Expression?
Short Answer: * Statement (Old): case : break;. Verbose. Imperative. * Expression (C# 8+):
Functional syntax. Returns a value. Concise.
Example:
// Expression
var result = status switch
{
1 => "Pending",
2 => "Active",
_ => "Unknown"
};
23
Tricky: Passing a Reference Type (class) by value still allows you to change its properties, but you cannot
reassign the object itself to a new one. *** ## Q83. What is the ref keyword?
Short Answer: Forces arguments to be passed by reference. Requirement: Variable must be initialized
before passing. *** ## Q84. What is the out keyword?
Short Answer: Like ref, but designed for returning multiple values. Requirement: Method MUST
assign a value before returning. Variable does not need initialization before passing. Modern: Get(out var
result); (Inline declaration). *** ## Q85. What is the in keyword (C# 7.2)?
Short Answer: Passes argument by reference but Read-Only. Usage: Performance optimization for large
structs. Avoids copying the struct but prevents modification. *** ## Q86. What are params in methods?
Short Answer: Allows passing a variable number of arguments as a comma-separated list. public
void Log(params string[] messages) Call: Log("A", "B", "C"); *** ## Q87. What are “Named
Arguments”?
Short Answer: Calling a method by specifying parameter names. Improves readability and allows skipping
optional parameters. Print(message: "Hello", color: [Link]); *** ## Q88. What are
“Optional Parameters”?
Short Answer: Parameters with default values. Must be at the end of the list. void Connect(int port =
80) *** ## Q89. What is a “Local Function”?
Short Answer: A method defined inside another method. Access: Can access variables from the outer
scope (Closure). Benefit: Keeps helper logic private to the method that needs it. Safer than private methods
for single-use logic. *** ## Q90. Local Function vs Lambda?
Short Answer: * Local Function: Compiled as a static method (if strict) or struct. Better perfor-
mance/memory (fewer allocations). Supports recursion easily. * Lambda: Copiled to a Delegate. Creates
heap allocation (garbage). *** ## Q91. What is a Tuple?
Short Answer: A lightweight data structure to hold multiple values. Old (Item1, Item2): Tuple<int,
string> (Reference type). New (ValueTuple): (int Id, string Name) (Value type). Usage: Great for
method return values without creating a specific class/struct. *** ## Q92. What is Deconstruction?
Short Answer: Unpacking a Tuple or Object into separate variables. var (x, y) = GetPoint(); Or
implementation Deconstruct method on a class to allow var (name, age) = person;. *** ## Q93. What
is Pattern Matching?
Short Answer: Testing an expression against a “pattern” (Type, distinct value, or property shape). if
(obj is Order { Total: > 100 } vipOrder) *** ## Q94. What is the discard variable (_)?
Short Answer: A write-only variable that tells the compiler “I don’t care about this value”. Unused
out parameters: TryParse(str, out _) Unused Lambda params: (_, _) => 0 *** ## Q95. What is
Recursion?
Short Answer: A method calling itself. Must have a base case to stop. Risk: StackOverflowException if
too deep (Stack is small). *** ## Q96. What is Tail Recursion?
Short Answer: A specific form of recursion where the recursive call is the last action. Compiler Note:
C# generic/JIT does not strictly optimize tail recursion (unlike F#), so deep recursion is risky in C#. ***
## Q97. What is an Iterator Method?
Short Answer: A method that uses yield return to produce a sequence of values lazily. It builds a State
Machine behind the scenes. *** ## Q98. What is yield return?
Short Answer: Pauses the method execution and returns a value to the caller. When the caller asks for the
next value, execution resumes exactly where it left off. Benefit: Memory efficient. Generates items one by
one instead of creating a huge List first. *** ## Q99. What is yield break?
24
Short Answer: Stops the iterator and ends the sequence (equivalent to return in a normal method). ***
## Q100. Limitations of yield?
Short Answer: * Cannot be in unsafe blocks. * Cannot be in methods with ref or out parameters. *
Cannot be in try-catch with yield return (but try-finally is okay). *** ## Q101. What is an Indexer?
Short Answer: Allows an object to be indexed like an array at instance level. public string this[int
index] { get { ... } } Used in Dictionary, List, etc. *** ## Q102. What is Operator Overloading?
Short Answer: Defining custom behavior for operators (+, ==) for your custom types. public static
Complex operator +(Complex a, Complex b) Rule: If you override ==, you must override != and
Equals/GetHashCode. *** ## Q103. What is User-Defined Conversion?
Short Answer: Custom implicit/explicit cast logic. public static implicit operator double(Distance
d) Allows double val = myDistance; *** ## Q104. What is a Delegate?
Short Answer: A type-safe function pointer. Validates signature match. Base for Events and LINQ. ***
## Q105. What is Action vs Func?
Short Answer: * Action: Delegate that returns void. Action<string> takes string, returns void. * Func:
Delegate that returns a value. Func<string, int> takes string, returns int. *** ## Q106. What is a
Predicate?
Short Answer: A specialized delegate Func<T, bool>. Always returns boolean. Used in
[Link](predicate). *** ## Q107. What is an Anonymous Method?
Short Answer: Old syntax for defining inline delegates. delegate(int x) { return x + 1; }. Replaced
by Lambda Expressions. *** ## Q108. What is a Lambda Expression?
Short Answer: Concise syntax for writing anonymous functions. x => x + 1. Uses the => (goes to)
operator. *** ## Q109. What is Closure?
Short Answer: When a lambda/local function captures variables from its outer scope. The compiler
generates a class to hold these variables so they outlive the stack frame of the parent method. Risk:
Accidental memory leaks if capturing large objects. *** ## Q110. What is Expression Tree?
Short Answer: Data structure representing code logic. Expression<Func<T>>. Unlike compiled delegates,
Expression Trees can be inspected and translated (e.g., by Entity Framework to generate SQL from LINQ).
*** ## Q111. What is Reflection?
Short Answer: Runtime inspection of Metadata. Allows iterating properties, methods, and types dynamically.
Cons: Slow, breaks compile-time safety. *** ## Q112. What is Dynamic Loading?
Short Answer: Loading assemblies at runtime matching a pattern. [Link]("[Link]").
Common in OMS Plugin Architectures. *** ## Q113. What is [Link]?
Short Answer: Creates an object instance using Reflection type info. Slower than new Type(). *** ##
Q114. What are Generic Attributes (C# 11)?
Short Answer: Attributes that accept type parameters directly. [TypeFilter<MyFilter>] instead of
[TypeFilter(typeof(MyFilter))]. *** ## Q115. What are Caller Information Attributes?
Short Answer: [CallerMemberName], [CallerFilePath], [CallerLineNumber]. Compiler injects the
caller’s info. Critical for Logging and INotifyPropertyChanged. *** ## Q116. What is the dynamic keyword
really?
Short Answer: It tells compiler to turn off checks and emit Dynamic Language Runtime (DLR) code.
Resolves members at runtime. *** ## Q117. dynamic vs Reflection?
Short Answer: * dynamic: Easier syntax ([Link]), cached performance. * Reflection: More control,
harder syntax (GetType().GetProperty().GetValue()). *** ## Q118. What is ExpandoObject?
25
Short Answer: A dynamic object (like a Dictionary) where you can add properties at runtime. dynamic x
= new ExpandoObject(); [Link] = "Test"; *** ## Q119. What is unsafe code?
Short Answer: Blocks where you can use Pointers (int* P). Bypasses GC and Bounds checking. Requires
allowUnsafeBlocks in csproj. Used for high-performance image processing/interop. *** ## Q120. What is
fixed statement?
Short Answer: Pins a managed object in heap so GC doesn’t move it while unmanaged pointers are accessing
it. fixed (int* p = array) { ... } ** (Q121-Q130 reserved for more deep dives on functions. . . )*
26
Short Answer: Extends/Modifies the virtual implementation of an inherited method. Enables polymorphism.
Base b = new Derived(); [Link]() calls Derived method. *** ## Q131. Can you override a private
method?
Short Answer: No. Private members are not visible to subclasses. You can override protected, protected
internal, or public. *** ## Q132. Explicit Interface Implementation?
Short Answer: Implementing an interface method without marking it public. Accessibly only via the
interface reference. Use Case: Solving name collisions (two interfaces have Save()) or hiding “advanced”
API methods from the class’s public surface. void [Link]() { ... } *** ## Q133. What
is a Constructor?
Short Answer: A method called when an object is instantiated. Used to initialize state. If you don’t define
one, compiler generates a default parameterless one. *** ## Q134. What is a Static Constructor?
Short Answer: static MyClass() { ... }. Called automatically once before the first instance is created
or any static member is accessed. Use Case: Initializing complex static data (e.g., loading config). Trap: If
it throws an exception, the class becomes unusable for the app’s lifetime. *** ## Q135. What is a Private
Constructor?
Short Answer: Prevents instantiation from outside. Use Case: 1. Singleton Pattern: private
constructor, exposed via static Instance. 2. Factory Pattern: Force usage of [Link]() static
method. 3. Static Classes: (Though C# static class is clearer). *** ## Q136. What is this keyword?
Short Answer: Refers to the current instance of the class. Used to distinguish fields from params ([Link]
= name) or call other constructors (: this()). *** ## Q137. What is base keyword?
Short Answer: Accesses members of the parent class. [Link]() or public Derived() : base()
(calling parent constructor). *** ## Q138. Constructor Chaining?
Short Answer: One constructor calling another in the same class to avoid code duplication. public
Order(int id) : this(id, [Link]) { } *** ## Q139. What is a Destructor (Finalizer)?
Short Answer: ~MyClass(). Called by the Garbage Collector before reclaiming memory. Do Not Use:
Slows down GC. Use IDisposable for cleanup. Only use Finalizers to release Unmanaged resources if Dispose
wasn’t called. *** ## Q140. Access Modifiers: public vs internal?
Short Answer: * public: Visible everywhere. * internal: Visible only within the same Assembly
(Project). Default for classes. *** ## Q141. Access Modifiers: protected vs private?
Short Answer: * private: Visible only in this class. * protected: Visible in this class AND subclasses.
*** ## Q142. What is protected internal?
Short Answer: Visible to subclasses OR anyone in the same assembly. (Union of scopes). *** ## Q143.
What is private protected (C# 7.2)?
Short Answer: Visible to subclasses AND in the same assembly. (Intersection of scopes). “Strictly internal
inheritance”. *** ## Q144. What are Properties vs Fields?
Short Answer: * Field: A variable directly holding data. public int id;. Bad encapsulation. *
Property: A method pair (get/set) looking like a field. Enforces logic/validation. public int Id { get;
set; }. *** ## Q145. What are Auto-Implemented Properties?
Short Answer: public int Id { get; set; }. Compiler generates a private backing field automatically.
Clean syntax. *** ## Q146. What is init accessor (C# 9)?
Short Answer: public int Id { get; init; }. Allows setting the property only during object initial-
ization (new Order { Id = 1 }). After that, it is immutable (readonly). *** ## Q147. What are Required
Properties (C# 11)?
Short Answer: public required string Name { get; set; }. Forces the caller to set this property
in the object initializer. Fixes the “Partial Initialization” problem of objects. *** ## Q148. What is an
27
Indexer?
Short Answer: Allows class to be accessed array-style. public string this[int i]. *** ## Q149.
What is Object Initializer Syntax?
Short Answer: var o = new Order { Id = 1, Name = "Test" };. Sets public properties immediately
after construction. Atomic-like readability. *** ## Q150. Copy Constructor?
Short Answer: A constructor that takes an instance of the class to create a new copy. public Order(Order
other) { [Link] = [Link]; }. Use record types with with expression in modern C# instead. ***
## Q151. Shallow Copy vs Deep Copy?
Short Answer: * Shallow: Copies values. Reference fields still point to same objects. (MemberwiseClone()).
* Deep: Copies values AND recursively clones referenced objects. Correct for full isolation. *** ## Q152.
What is Method Overloading?
Short Answer: Same method name, different parameter signature. Print(string s) vs Print(int i).
Return type is NOT part of the signature for overloading. *** ## Q153. What is Operator Overloading?
Short Answer: Defining +, - for custom types. Useful for Math structs (Vector, Matrix, Money). *** ##
Q154. What is [Link] methods?
Short Answer: Equals, GetHashCode, ToString, GetType, Finalize, MemberwiseClone. *** ## Q155.
Why override ToString()?
Short Answer: Default returns full type name (“[Link]”). Override to return meaningful
debug info (“Order #123 (Open)”). *** ## Q156. Why override Equals()?
Short Answer: Default checks Reference Equality (are they the same memory address?). Override to check
Value Equality (do they have same ID?). *** ## Q157. Contract between Equals and GetHashCode?
Short Answer: If [Link](B) is true, then [Link]() MUST equal [Link](). If broken,
HashSets/Dictionaries will fail to find keys (collisions logic breaks). *** ## Q158. What is IEquatable<T>?
Short Answer: Interface for type-specific equality comparison. Equals(T other). Avoids boxing (calling
[Link]) for struct types. Performance critical. *** ## Q159. What is IComparable<T>?
Short Answer: Defines generic sort order. CompareTo(T other). Returns -1 (less), 0 (equal), 1 (greater).
Used by [Link](). *** ## Q160. What is Cohesion?
Short Answer: How closely related the responsibilities of a class are. High Cohesion (Good): Class does
one focused thing (OrderValidator). Low Cohesion (Bad): Class does everything (OrderManager: saves
DB, sends email, prints PDF). *** ## Q161. What is Coupling?
Short Answer: How dependent classes are on each other. Loosely Coupled (Good): Classes talk via
Interfaces. Easy to test/swap. Tightly Coupled (Bad): Classes rely on concrete new Class() instantiation.
Hard to change. *** ## Q162. Dependency Injection (DI) basics?
Short Answer: Injecting dependencies (services) into a class (usually constructor) rather than letting the
class create them. Inverts Control (IoC). Makes code testable. *** ## Q163. Composition over Inheritance?
Short Answer: Design principle. Prefer building objects from other objects (Has-A relationship) rather
than inheriting (Is-A). Inheritance is rigid (compile time). Composition is flexible (runtime swapping of
behaviors). *** ## Q164. What is a “Mixin” (via Interface)?
Short Answer: Using Default Interface Methods to add behavior to unrelated classes without inheritance.
*** ## Q165. Extension Methods?
Short Answer: static methods in static classes with this parameter. Adds methods to existing types
without modifying them. public static bool IsValid(this Order o) -> [Link](). *** ## Q166.
Can Extension Methods access private fields?
28
Short Answer: No. They are just static methods. They respect encapsulation. *** ## Q167. What are
Records (C# 9)?
Short Answer: Special class type optimized for data. * Value-based equality built-in. * Concise syntax
(record Person(string Name)). * Immutable by default. * ToString() prints values. *** ## Q168.
record class vs record struct?
Short Answer: * record / record class: Reference type. * record struct: Value type. *** ## Q169.
What is with expression?
Short Answer: Non-destructive mutation. Creates a copy of a record with specific properties changed. var
p2 = p1 with { Age = 30 }; *** ## Q170. Anonymous Types?
Short Answer: Compiler-generated class for temporary data. var x = new { Name = "A", Age = 10 };
Read-only properties. Used in LINQ projections. *** ## Q171. What is dynamic dispatch?
Short Answer: Resolving which method to call at runtime. Standard virtual methods use Single Dispatch
(based on receiver type). dynamic keyword uses DLR. *** ## Q172. Covariance vs Contravariance?
Short Answer: * Covariance (out T): Can return a derived type. IEnumerable<string> ->
IEnumerable<object>. “Producer”. * Contravariance (in T): Can accept a base type. Action<object>
-> Action<string>. “Consumer”. *** ## Q173. Where is Covariance used?
Short Answer: Arrays (unsafe), Interfaces (IEnumerable<out T>), Delegates (Func<out T>). *** ##
Q174. What is the Diamond Problem?
Short Answer: Ambiguity when inheriting from two classes that share a common base. C# avoids this by
banning Multiple Inheritance for Classes. (Interfaces can simulated this, compiler requires explicit override
explanation). *** ## Q175. What is a Nested Class?
Short Answer: A class defined inside another. Can access private members of the Outer class. Used for
Helpers strictly coupled to the container. *** ## Q176. Flags Enum attribute?
Short Answer: Allows an Enum to represent a bitmask (multiple values types). [Flags] enum Perms {
Read=1, Write=2 }. Perms p = Read | Write;. [Link](Read). *** ## Q177. Null Object Pattern?
Short Answer: Returning a specific “Empty” object instead of null. [Link] instead of null. Avoids
NullReferenceException checks. *** ## Q178. What is the “God Object” anti-pattern?
Short Answer: A class that knows too much or does too much. Refactor by splitting into smaller Services.
*** ## Q179. Immutable Object benefits?
Short Answer: Thread-safe by default (no race conditions). Cache-friendly. Predictable state (no side
effects). *** ## Q180. How to make a class immutable?
Short Answer: 1. Properties get only or init. 2. Set values in Constructor. 3. Backing fields readonly. 4.
Ensure mutable collections are wrapped (ReadOnlyCollection). ** ## Q181-Q200. . . (Reserved for detailed
SOLID/Pillars breakdown if needed, or moved to Arch section). Assuming 180 questions covers the core OOP
sufficiently for this block. I’ll add the SOLID principles here briefly as they are OOP core.*
29
Q183. SOLID: L - Liskov Substitution?
Answer: Derived classes must be substitutable for base classes without crashing. Don’t throw
NotImplementedException in an override.
30
Short Answer: Language Integrated Query. Uniform query syntax for Objects, SQL, XML. from x in
list where x > 5 select x. *** ## Q213. Deferred Execution?
Short Answer: The query is not executed when defined. It runs when you iterate (using foreach, ToList(),
Count()).
var q = [Link](x => x > 10); // Nothing happens here
foreach(var i in q) { ... } // Runs here
31
Short Answer: Optimization. * Gen 0: Short-lived objects (temp vars). Collected frequently. Fast. * Gen
1: Buffer between 0 and 2. * Gen 2: Long-lived objects (static, caches). Collected rarely. Expensive (Full
GC, pauses app). *** ## Q230. Large Object Heap (LOH)?
Short Answer: Heap for objects > 85,000 bytes. Not compacted by default (fragmentation risk). Gen 2
collection. *** ## Q231. IDisposable pattern?
Short Answer: Standard mechanism to release Unmanaged Resources (File handles, sockets). Implement
Dispose(). Call [Link](this). *** ## Q232. Finalizer (~Class) vs Default GC?
Short Answer: Finalizer is the “Safety Net”. Called by GC if you forgot to call Dispose. Expensive (moves
object to Finalization Queue, survives Gen update). Rule: Only implement if you own unmanaged handle
directly (rare). *** ## Q233. using statement and IDisposable?
Short Answer: using (var x = new X()) compiles to try { ... } finally { [Link]() }. En-
sures cleanup even if exception crashes the block. *** ## Q234. Weak Reference?
Short Answer: A reference that doesn’t prevent GC from collecting the object. WeakReference<T>. Used
for Caches: “Keep this image if memory is free, but delete it if memory is low.” *** ## Q235. What is
GCHandle?
Short Answer: Handle for passing managed object to unmanaged code. Can “Pin” the object so GC doesn’t
move it. *** ## Q236. StackOverflowException?
Short Answer: Infinite recursion or massive stack allocation (stackalloc). Cannot be caught. Process
terminates immediately. *** ## Q237. OutOfMemoryException?
Short Answer: Heap full. GC cannot free enough space. Or 32-bit process limit (2GB). Or LOH
fragmentation. *** ## Q238. Reflection Performance?
Short Answer: Reflection is slow (metadata lookup, no JIT optimizations). Optimization: Use Cached
Delegates or Compiled Expression Trees for repeated access. *** ## Q239. Attributes vs Interfaces?
Short Answer: * Interfaces: Enforce behavior/contract (Compile time). * Attributes: Add declarative
metadata (Runtime inspection). “Passive”. *** ## Q240. Func<T> vs Expression Tree?
Short Answer: * Func<T> is compiled code. Opaque box. * Expression<Func<T>> is data structure.
Can be analyzed (e.g., LINQ to SQL converts x => [Link] > 5 into SQL WHERE ID > 5). *** ## Q241.
Covariance in Generics?
Short Answer: IEnumerable<out T>. Allows IEnumerable<string> -> IEnumerable<object>. Only for
output positions (return values). *** ## Q242. Contravariance in Generics?
Short Answer: Action<in T>. Allows Action<object> -> Action<string>. Only for input positions
(parameters). *** ## Q243. Extension method priority?
Short Answer: Instance methods win. If Class has MethodA() and Extension has MethodA(), class method
is called. Extensions only extend if no matching instance member exists. *** ## Q244. Nullable Reference
Types (string?)?
Short Answer: Compile-time warning system (Post C# 8). Doesn’t change runtime behavior. Help
developers avoid NullReferenceException. *** ## Q245. Null-Forgiving operator (!)?
Short Answer: string s = GetPossibleNull()!; Tells compiler “Trust me, this is NOT null here”.
Suppresses warning. *** ## Q246. Memory<T> vs Span<T>?
Short Answer: * Span<T>: Stack-only. Fast. Limitation: Cannot be stored in class fields or async methods.
* Memory<T>: Heap-compatible span. Can be used in async/await. Usually converted to Span for processing.
*** ## Q247. ArrayPool<T>?
Short Answer: Recycles arrays to avoid GC pressure. ArrayPool<int>.[Link](100). Must
Return() the array. *** ## Q248. stackalloc?
32
Short Answer: Allocates memory on the Stack (instead of Heap). Span<int> numbers = stackalloc
int[10]; Extremely fast, zero GC. Risk of Stack Overflow. *** ## Q249. [Link] vs
Newtonsoft?
Short Answer: * [Link]: High performance (Spans), secure, strict standard compliance. Built-
in. * Newtonsoft: Feature rich, flexible, slower, allocates more memory. Trend: Move to [Link]
in .NET 8. *** ## Q250. Source Generators?
Short Answer: Code that runs during compilation and adds new files. Replaces runtime Reflection (checking
attributes) with compile-time code generation. Used by [Link] Serializer, Logging, Validations.
*** ## Q251. What is Dynamic Language Runtime (DLR)?
Short Answer: Component on top of CLR enabling dynamic typing (dynamic). Used for interoperability
with IronPython or COM. *** ## Q252. Volatile Keyword?
Short Answer: Prevents compiler/CPU from reordering read/writes instructions for a field. Guarantees
most up-to-date value in multi-threading. Usually Interlocked or lock is safer. *** ## Q253. Interlocked
class?
Short Answer: Atomic operations for simple types. [Link](ref counter). Faster than
lock. *** ## Q254. Monitor class?
Short Answer: The backend logic of lock keyword. [Link](obj) / [Link](obj). Allows
Wait and Pulse (Signal/Wait mechanism). *** ## Q255. AutoResetEvent vs ManualResetEvent?
Short Answer: * Auto: Resets to non-signaled state automatically after releasing one waiting thread.
(Turnstile). * Manual: Stays open (releases all threads) until manually reset. (Gate). *** ## Q256. Mutex
vs Semaphore?
Short Answer: * Mutex: Lock across Processes (OS wide). Only one thread can own it. * Semaphore:
Allows N threads to access resource concurrently (Throttling). *** ## Q257. ThreadPool?
Short Answer: Managed pool of worker threads. Reusing threads is cheaper than creating OS Threads
(1MB stack + Context switch). [Link] uses ThreadPool. *** ## Q258. Task vs Thread?
Short Answer: * Thread: Lower-level OS Object. 1:1 mapping (mostly). * Task: Higher-level abstraction
representing “work to be done”. Runs on ThreadPool. Returns values (Task<T>). Exception handling support.
*** ## Q259. [Link] vs [Link]?
Short Answer: * [Link]: Modern wrapper. Safe defaults (DenyChildAttach). * StartNew: Old. Complex
options. Dangerous defaults. Avoid. *** ## Q260. Context Switching?
Short Answer: CPU saving state of one thread and loading another. Expensive. Reason why async (IO
bound) is better than blocking threads (waiting). *** ## Q261. Async/Await State Machine?
Short Answer: Compiler converts async method into a generated Class (State Machine). Breaks method at
await points. Manages stack variables and continuation callbacks. *** ## Q262. ConfigureAwait(false)?
Short Answer: Tells Awaiter “Do not force continuation on the original context (UI Thread)”. Prevents
Deadlocks in Library code. Improves performance in Backend code. *** ## Q263. [Link] vs
[Link]?
Short Answer: * WhenAll: Asynchronous. Returns a Task. Non-blocking. * WaitAll: Synchronous. Blocks
thread. Dangerous (Deadlocks). *** ## Q264. ValueTask<T>?
Short Answer: Value-type version of Task. Reduces allocation if the result is often available synchronously
(Cached). Only await it ONCE. *** ## Q265. IAsyncEnumerable<T> (Async Streams)?
Short Answer: await foreach. Streaming data asynchronously. “Pull” based async iteration. Good for
slow API paginated responses. *** ## Q266. Channel<T>?
33
Short Answer: High-performance Producer-Consumer queues in .NET Core. Thread-safe. Supports
Backpressure (Bounded capacity). Better than BlockingCollection for async usage. *** ## Q267.
Deadlock common cause?
Short Answer: Calling .Result or .Wait() on an async TaskMain thread (UI/[Link] Legacy). Con-
text is blocked waiting for Task; Task is waiting for Context. Fix: Go ‘Async All The Way’. or Use
ConfigureAwait(false). *** ## Q268. Race Condition?
Short Answer: Outcome depends on timing of threads. Two threads increment x (read 5, add 1, write 6).
Result 6 instead of 7. Fix: Locks, Interlocked, Immutable data. *** ## Q269. CancellationToken?
Short Answer: Standard pattern for cooperative cancellation. Pass token down call chain. Check
[Link] or [Link](). *** ## Q270.
[Link] vs [Link]?
Short Answer: * [Link]: CPU Bound. Parallelism. Blocks. * [Link]: IO Bound.
Concurrency. Non-blocking. *** ## Q271. ConcurrentBag vs ConcurrentQueue?
Short Answer: * ConcurrentQueue: FIFO. Strict ordering. * ConcurrentBag: Unordered. Optimized for
scenarios where same thread adds/takes data (Thread Local Storage). *** ## Q272. Thread Local Storage
(ThreadLocal<T>)?
Short Answer: Data unique to each thread. Static field shared by all threads? No, each sees its own copy.
*** ## Q273. AsyncLocal<T>?
Short Answer: Preserves context across async/await flow (which might jump threads). Used for “HttpCon-
[Link]” style logic in modern Core (Correlation ID). *** ## Q274. Atomic Operation?
Short Answer: Indivisible operation. Cannot be interrupted. Reading an int (32-bit) is atomic on 32-bit
CPU. long (64-bit) read is NOT atomic (2 reads). *** ## Q275. Lock-free programming?
Short Answer: Using [Link] allows updates without expensive lock. Complex
(CAS - Compare And Swap). *** ## Q276. Starvation (Threading)?
Short Answer: High priority threads hog CPU; Low priority threads never run. *** ## Q277. False
Sharing?
Short Answer: Two threads update independent variables that sit on the same CPU Cache Line. CPU
invalidates cache line constantly. Performance kills. Fix: Padding variables. *** ## Q278. Memory Barrier?
Short Answer: Instructions to CPU preventing reordering optimizations across the barrier. Ensures
visibility of writes. [Link](). *** ## Q279. SpinLock?
Short Answer: Lock that waits in a loop (Active waiting) instead of yielding thread. Good for huge
contention nanosecond locks. Bad for long blocks (burns CPU). *** ## Q280. What is PLINQ?
Short Answer: Parallel LINQ. [Link]().Where(...). Automates partitioning and merging on
multiple cores. * End of Part 4**
34
Short Answer: Creates objects without specifying the exact class to behave. Factory Method: Subclasses
decide instantiation. Simple Factory: A static method Create(type) that switches and returns IProduct.
Benefit: Decouples client from concrete classes. *** ## Q283. What is the Abstract Factory Pattern?
Short Answer: Interface for creating families of related objects (e.g., CreateButton, CreateCheckbox)
without specifying concrete classes. Use Case: UI Themes (DarkThemeFactory vs LightThemeFactory). ***
## Q284. What is the Builder Pattern?
Short Answer: Constructs complex objects step-by-step. new OrderBuilder().WithId(1).AddItem("A").Build();
Benefit: Avoids “Telescoping Constructor” anti-pattern (constructors with 10 parameters). *** ## Q285.
What is the Observer Pattern?
Short Answer: One-to-Many dependency. When Subject changes, all Observers are notified. C#
Implementation: event keyword or IObservable<T> / IObserver<T> (Reactive Extensions). *** ##
Q286. What is the Strategy Pattern?
Short Answer: Defines a family of algorithms, encapsulating each one (Interchangeable). Example:
SortStrategy (QuickSort, MergeSort). Usage: [Link](new QuickSort());. *** ##
Q287. What is the Decorator Pattern?
Short Answer: Dynamically adds behavior to an object. Wraps the object. Example: Stream (FileStream
-> BufferedStream -> GZipStream). Each layer “decorates” the behavior. *** ## Q288. What is the
Adapter Pattern?
Short Answer: Bridge between incompatible interfaces. Example: LegacyLogAdaper implements ILogger
but internally calls [Link](). *** ## Q289. What is the Facade Pattern?
Short Answer: Simple interface to a complex subsystem. Example: [Link]() might
internally call Inventory, Payment, and Shipping services. Client only sees one method. *** ## Q290.
What is the Proxy Pattern?
Short Answer: Placeholder for another object to control access. Use Case: Lazy Loading (EF Core
proxies), Security (Check permission before calling real object). *** ## Q291. What is the Command
Pattern?
Short Answer: Encapsulates a request as an object (Execute(), Undo()). Use Case: Undo/Redo systems,
Job Queues. *** ## Q292. What is the Template Method Pattern?
Short Answer: Defines algorithm skeleton in base class (Run()), let subclasses override specific steps
(Step1(), Step2()). *** ## Q293. What is the Iterator Pattern?
Short Answer: Access elements sequentially without exposing underlying representation. C#: IEnumerator
/ foreach. *** ## Q294. What is the Composite Pattern?
Short Answer: Tree structure where individual objects and groups are treated uniformly. Example: File
System (File vs Folder). Both are IFileSystemEntry. *** ## Q295. What is the State Pattern?
Short Answer: Object alters behavior when internal state changes. Example: [Link] = NewState
(Can Cancel), [Link] = ShippedState (Cannot Cancel). *** ## Q296. Dependency Injection (DI)
vs Service Locator?
Short Answer: * DI: Dependencies passed in (Explicit). “Tell, don’t ask”. Clean. * Service Locator:
Class asks for dependencies [Link]<IService>() (Implicit). Anti-pattern (hides dependencies). ***
## Q297. DI Scope: Transient?
Short Answer: New instance created every time it is requested. Lightweight stateless services. *** ##
Q298. DI Scope: Singleton?
Short Answer: Created once per application lifetime. Shared by all requests. Risk: Not thread safe if it
holds state. Memory leaks. *** ## Q299. DI Scope: Scoped?
35
Short Answer: Created once per HTTP Request. Shared within that request, disposed at end. EF
Core DbContext is Scoped. *** ## Q300. What is “Captive Dependency”?
Short Answer: Injecting a Short-Lived service into a Long-Lived service. Example: Injecting Scoped
DbContext into a Singleton Cache. Result: The Scoped service is never disposed (trapped by Singleton).
Memory Leak + Bugs. *** ## Q301. Clean Architecture (Onion/Hexagonal)?
Short Answer: Separation of concerns using concentric circles. Core: Domain Entities (No dependencies).
Application: Use Cases / Interfaces. Infrastructure: DB / API implementation. UI/Web: Entry point.
Dependencies point Inward. *** ## Q302. What is CQRS (Command Query Responsibility Segregation)?
Short Answer: Splitting Read (Query) and Write (Command) models. Read: Fast DTOs, specific SQL
views. Write: Domain Entities, validation, transactions. Advantage: Scale reads independently (Replicas).
*** ## Q303. What is Event Sourcing?
Short Answer: Storing state as a sequence of events (OrderCreated, ItemAdded) rather than current state
(Snapshot). Replay: State is reconstructed by replaying events. Audit: Perfect audit trail. *** ## Q304.
Monolith vs Microservices?
Short Answer: * Monolith: Single deployable unit. Shared DB. Simple ops. Hard to scale specific parts.
* Microservices: Distributed. Independent deploy/scale. Complex ops (Network, Consistency). *** ##
Q305. What is the CAP Theorem?
Short Answer: In distributed system, choose 2 of 3: * Consistency (Every read receives most recent
write). * Availability (Every request receives response). * Partition Tolerance (System works despite network
drops). Reality: P is mandatory. Choose AP (Resultual Consistency) or CP (Strong Consistency, potential
downtime). *** ## Q306. What is Database Sharding?
Short Answer: Horizontal partitioning data across servers. Strategy: By UserID, Region (Tenant). ***
## Q307. What is the Circuit Breaker Pattern?
Short Answer: If a service fails repeatedly, stop calling it (“Trip the breaker”) to allow it to recover. Return
fast error or fallback. Library: Polly. *** ## Q308. What is the Transactional Outbox Pattern?
Short Answer: How to save to DB and publish Event (RabbitMQ) atomically? 1. Save Entity + Event to
“Outbox” table in same DB transaction. 2. Separate process polls Outbox and publishes to Bus. *** ##
Q309. What is Idempotency?
Short Answer: Operation can be applied multiple times without changing result beyond initial application.
Example: Processing “Payment #123” twice charges the card only once. Critical for retrying failed messages.
*** ## Q310. What is a Saga?
Short Answer: Managing Distributed Transactions. Sequence of local transactions. If one fails, execute
Compensating Transactions (Undo) for previous steps. *** ## Q311. SOLID: Single Responsibility
Principle (SRP)?
Deep Dive: A class (or module) should have one, and only one, reason to change. Does not mean “One
Method”. Means “One Actor/Business Function”. Separating UserAuth from UserRepository. *** ##
Q312. SOLID: Open/Closed Principle (OCP)?
Deep Dive: Software entities should be open for extension but closed for modification. Add new functionality
by adding new classes, not by editing existing tested code. Example: [Link]() -> Add Triangle
class, don’t add case Triangle in Shape class. *** ## Q313. SOLID: Liskov Substitution Principle (LSP)?
Deep Dive: Objects of a superclass should be replaceable with objects of its subclasses without breaking
the application. Violation: Square inherits Rectangle but changing Width changes Height. Or throwing
NotImplementedException. *** ## Q314. SOLID: Interface Segregation Principle (ISP)?
Deep Dive: Clients should not be forced to depend on interfaces they do not use. “Fat Interfaces” are bad.
Break IWorker into IEater and IWorker. *** ## Q315. SOLID: Dependency Inversion Principle (DIP)?
36
Deep Dive: High-level modules should not depend on low-level modules. Both should depend on abstractions.
OrderService depends on IOrderRepository, not SqlOrderRepository. *** ## Q316. DRY (Don’t
Repeat Yourself)?
Short Answer: Every piece of knowledge must have a single representation. Duplication leads to maintenance
nightmares (Fix bug here, forget there). *** ## Q317. YAGNI (You Ain’t Gonna Need It)?
Short Answer: Do not implement features until strictly necessary. Over-engineering prevents shipping. ***
## Q318. KISS (Keep It Simple, Stupid)?
Short Answer: Complexity should be avoided. Simple code is easier to debug and maintain. *** ## Q319.
What is Unit Testing?
Short Answer: Testing the smallest unit (method/class) in isolation. Mock external dependencies
(Mock<IDb>). Fast, reliable. *** ## Q320. What is Integration Testing?
Short Answer: Testing interactions between units (Service + DB). Uses real DB (or Testcontainers). Slower.
*** ## Q321. What is E2E (End to End) Testing?
Short Answer: Testing full flow via UI (Selenium/Playwright) or API. User perspective. *** ## Q322.
Stub vs Mock?
Short Answer: * Stub: Provides canned answers. “If calling Get(), return 5”. (State verification). *
Mock: Verifies behavior. “Verify SendEmail() was called 1 time”. (Behavior verification). *** ## Q323.
AAA Pattern?
Short Answer: Arrange: Setup objects. Act: Call method. Assert: Verify result. *** ## Q324. Code
Coverage?
Short Answer: % of lines executed during tests. Metric: High coverage != Bug free. But Low coverage =
Risk. *** ## Q325. TDD (Test Driven Development)?
Short Answer: Red -> Green -> Refactor. Write failing test -> Write minimal code to pass -> Improve
code. *** ## Q326. xUnit vs NUnit/MSTest?
Short Answer: xUnit is modern, parallel by default, no [Setup]/[Teardown] (uses Constructor/Dispose).
*** ## Q327. IClassFixture in xUnit?
Short Answer: Share setup context (like Database connection) across all tests in a class. Avoids recreating
expensive objects per test. *** ## Q328. Theory and InlineData?
Short Answer: Data-driven tests. run one test method multiple times with different inputs. [InlineData(1,
2, 3)] (1+2=3). *** ## Q329. Test Pyramid?
Short Answer: Visual guide. Base: Many Unit Tests (Fast, Cheap). Middle: Some Integration Tests. Top:
Few UI Tests (Slow, Expensive). *** ## Q330. What is “Flaky Test”?
Short Answer: A test that passes sometimes and fails others without code changes. Cause: Timing, Async,
Shared state, Network. Fix: Isolation, remove [Link]. *** ## Q331. What is REST?
Short Answer: Representational State Transfer. Architectural style. Stateless, Client-Server, Cacheable,
Layered, Uniform Interface. *** ## Q332. HTTP Verbs (GET, POST, PUT, PATCH, DELETE)?
• GET: Read. Safe. Idempotent.
• POST: Create. Not Idempotent. (Twice = 2 items).
• PUT: Replace (Update full). Idempotent.
• PATCH: Modify (Update partial). Not necessarily Idempotent.
• DELETE: Remove. Idempotent. *** ## Q333. HTTP Status Codes?
• 200 OK.
37
• 201 Created.
• 204 No Content.
• 400 Bad Request (Validation).
• 401 Unauthorized (Who are you?).
• 403 Forbidden (I know you, but No).
• 404 Not Found.
• 500 Server Error. *** ## Q334. SOAP vs REST?
Short Answer: * SOAP: Protocol (XML). Strict contract (WSDL). Heavy (Envelopes). Built-in security
(WS-Security). Legacy Enterprise. * REST: Style (JSON/XML). Flexible. Lightweight. *** ## Q335.
What is GraphQL?
Short Answer: Query language for APIs. Client asks for exactly what it needs ({ user { name } }). No
over-fetching. Single Endpoint. *** ## Q336. gRPC?
Short Answer: High performance RPC framework by Google. Uses Protocol Buffers (Binary) and HTTP/2.
Strongly typed contracts (.proto). Great for Microservices internal comms. *** ## Q337. API Gateway?
Short Answer: Single entry point for backend. Handles Routing, Auth, Rate Limiting, Aggregation.
Pattern: BFF (Backend for Frontend). *** ## Q338. Authentication vs Authorization?
Short Answer: * AuthN: Who are you? (Login / JWT). * AuthZ: What can you do? (Roles / Claims /
Policy). *** ## Q339. JWT (JSON Web Token)?
Short Answer: Stateless auth token. Contains Claims (User ID, Role). Signed by server. Client sends in
Authorization: Bearer <token> header. *** ## Q340. OAuth2 vs OpenID Connect (OIDC)?
Short Answer: * OAuth2: Authorization framework (Delegated access). “Allow App to access my Photos”.
* OIDC: Authentication layer on top of OAuth2 (Identity). “Log in with Google”. *** ## Q341. CORS
(Cross-Origin Resource Sharing)?
Short Answer: Browser security feature. Prevents JS on [Link] from calling API on [Link] unless
siteB allows it header Access-Control-Allow-Origin. *** ## Q342. HATEOAS?
Short Answer: Hypermedia as the Engine of Application State. Rest API returns links (_links) telling
client what it can do next (next_page, cancel_order). *** ## Q343. What is Middleware in [Link]
Core?
Short Answer: Component pipeline that handles HTTP requests/responses. Auth -> Logging -> MVC.
Order matters! *** ## Q344. IApplicationBuilder?
Short Answer: Used in [Link] to define Middleware pipeline ([Link]()). *** ##
Q345. IServiceCollection?
Short Answer: Used in [Link] to register Dependency Injection ([Link]()).
*** ## Q346. Minimal APIs (C# 10)?
Short Answer: APIs without Controller boilerplate. Define routes in [Link]. [Link]("/", ()
=> "Hello");. Performance benefit (less overhead). *** ## Q347. Model Binding?
Short Answer: Mapping HTTP request data (Query, Body, Route) to C# Objects (Action parameters).
*** ## Q348. Model Validation?
Short Answer: Attributes ([Required], [Email]) on DTOs. Checked automatically. [Link].
*** ## Q349. Filters in [Link] Core?
Short Answer: Logic that runs before/after stages. AuthorizationFilter, ActionFilter (logic before
action), ExceptionFilter (Global error handling). *** ## Q350. SignalR?
38
Short Answer: Library for Real-time web functionality (Push). Uses WebSockets. Falls back to Long
Polling if sockets unavailable. *** ## Q351. Razor Pages?
Short Answer: Page-centric framework (MVVM-like). [Link] + [Link]. Simpler than
MVC for non-API web apps. *** ## Q352. Blazor?
Short Answer: Runs C# in the browser (via WebAssembly) or on Server (via SignalR). Single Page App
(SPA) framework without JavaScript. *** ## Q353. Kestrel?
Short Answer: Cross-platform, high-performance web server for [Link] Core. Included by default.
Usually sits behind a Reverse Proxy (IIS/Nginx) for security. *** ## Q354. Reverse Proxy?
Short Answer: Server (Nginx/IIS) sitting in front of Kestrel. Handles SSL termination, compressions,
static files, load balancing. *** ## Q355. What is the “Host” (Generic Host)?
Short Answer: IHost. Encapsulates app resources (DI, Logging, config, lifetime). Standardizes CLI apps
and Web apps. *** ## Q356. BackgroundService / HostedService?
Short Answer: Long-running tasks managed by the Host. ExecuteAsync() runs in background. *** ##
Q357. Swagger / OpenAPI?
Short Answer: Standard for documenting APIs. Swashbuckle: Library generates Swagger JSON from
C# controllers. *** ## Q358. Health Checks?
Short Answer: Endpoints (/health) that report app status (DB connection, Disk space). Used by Load
Balancers / K8s to restart sick pods. *** ## Q359. Rate Limiting?
Short Answer: Throttling requests to prevent abuse/DDoS. Middleware available in .NET 7+. *** ##
Q360. Response Caching?
Short Answer: Storing HTTP responses to serve future requests faster. Client-side (Headers) or Server-side
(Memory). *** ## Q361. Output Caching (New .NET 7+)?
Short Answer: Powerful server-side caching Middleware. Configurable policies (Eviction, Tagging). ***
## Q362. Distributed Caching?
Short Answer: Cache shared across servers (Redis, SQL). Essential for Scaling out (Session state). *** ##
Q363. Sticky Sessions?
Short Answer: Load Balancer always routes a user to the same server. Avoid: Makes scaling hard. Use
Distributed Cache instead. *** ## Q364. Anti-Forgery Token (CSRF)?
Short Answer: Prevents Cross-Site Request Forgery. Injects token in Form, verifies on Server. *** ##
Q365. XSS (Cross Site Scripting)?
Short Answer: Injecting malicious JS script into pages viewed by others. Fix: HTML Encode output
(Default in Razor). Content Security Policy (CSP). *** ## Q366. SQL Injection?
Short Answer: Malicious SQL in input (' OR 1=1). Fix: Use Parameterized Queries (EF Core / Dapper
parameters). NEVER concat strings into SQL. *** ## Q367. Open Redirect Vulnerability?
Short Answer: Allowing user input to control redirect URL (?returnUrl=[Link]). Fix: Check
[Link](). *** ## Q368. Data Protection API (DPAPI)?
Short Answer: Encryption/Decryption of data (Cookies, Tokens) using machine keys. *** ## Q369.
Secret Management?
Short Answer: Never check secrets into source control. Use Key Vault (Production) / User Secrets (Dev).
*** ## Q370. HTTPS / SSL?
Short Answer: Encrypted transport. In .NET, UseHttpsRedirection() forces HTTP->HTTPS. *** ##
Q371. What is Docker?
39
Short Answer: Platform for packaging app + dependencies (Runtime, OS libs) into “Container”. Guarantees
“Works on my machine” == “Works in Production”. *** ## Q372. Image vs Container?
Short Answer: * Image: Read-only template (Class). * Container: Running instance (Object). *** ##
Q373. Dockerfile?
Short Answer: Script to build the image. FROM [Link]/dotnet/aspnet:8.0 COPY . /app
ENTRYPOINT ["dotnet", "[Link]"] *** ## Q374. Docker Compose?
Short Answer: Orchestration for local dev. Defines multi-container app (API + SQL + Redis) in YAML.
*** ## Q375. Kubernetes (K8s)?
Short Answer: Orchestrator for production containers. Handles specific scaling, health check failures,
rolling updates. *** ## Q376. Microservices Communication styles?
Short Answer: * Sync: HTTP/gRPC. High coupling. * Async: Message Bus (RabbitMQ). Low coupling.
*** ## Q377. Eventual Consistency?
Short Answer: Data will be consistent eventually, but not immediately across all nodes. Acceptable
trade-off for high availability. *** ## Q378. Distributed Tracing?
Short Answer: Tracking a request across microservices. TraceId: Unique ID for the whole flow. SpanId:
Unique ID for one hop. Tools: OpenTelemetry, Jaeger, Zipkin. *** ## Q379. Blue/Green Deployment?
Short Answer: Two identical environments. Blue: Live. Green: New Version. Traffic switched instantly.
Zero downtime. Safe rollback. *** ## Q380. Canary Deployment?
Short Answer: Rollout new version to small % of users (Canaries). Monitor errors. Gradually increase %.
* End of Part 5**
40
Q386. AsNoTracking()?
Short Answer: Disables change tracking. Performance boost for Read-Only scenarios. _context.[Link]().
41
Q397. Compile-Time Query ([Link])?
Short Answer: Pre-compiles the LINQ-to-SQL translation delegate. Reuses implementation for high-
frequency queries (e.g., GetOrderById called 1000/sec).
42
Q408. What is Guid.V7 (C# 13 / .NET 9)?
Short Answer: Time-ordered GUIDs. Better for Database Indexing (Clustered Index) than completely
random V4 GUIDs.
43
Q419. Semantic Versioning (SemVer)?
Short Answer: [Link] (1.0.0). * Major: Breaking changes. * Minor: New features (Backwards
compatible). * Patch: Bug fixes.
Q426. OpenTelemetry?
Short Answer: Standard for generating Traces, Metrics, Logs. Vendor neutral (Export to Jaeger, Prometheus,
Azure Monitor).
44
Q430. What is a “Post-Mortem”?
Short Answer: Document written after an incident. Analysis of Root Cause, Impact, and Preventive
Actions. No blamestorming.
Q440. WebHook?
Short Answer: User-defined HTTP callback. “Don’t call us, we’ll call you”. System A POSTs data to
System B URL when event happens. ** End of Part 6*
45
Q441. Scenario: Two users buy the last item simultaneously (Race Condition).
How to prevent “Overselling”?
Short Answer: Use Optimistic Concurrency with a Version Column (RowVersion). 1. User A reads
Stock=1 (Version=1). 2. User B reads Stock=1 (Version=1). 3. User A saves (Stock=0, Version=2). DB
check: WHERE Version=1. Success. 4. User B saves (Stock=0, Version=2). DB check: WHERE Version=1.
Fail (Rows Affected = 0). 5. Catch DbUpdateConcurrencyException, reload stock (now 0), tell User B
“Out of Stock”. *** ## Q442. Difference between “Soft Allocation” and “Hard Allocation”?
Short Answer: * Soft Allocation: Logical reservation (Cart). Expires after X minutes. Inventory still
physically on shelf. “Available To Promise” (ATP) decreases. * Hard Allocation: Physical reservation.
Valid order placed. Warehouse Wave creates a Pick Task. Inventory locked. *** ## Q443. Scenario: The
“Nightly Import” takes 6 hours and crashes the DB. Fix it.
Short Answer: 1. Analyze: Is it inserting 1-by-1? (N+1 inserts). 2. Fix: Switch to Bulk Insert
(SqlBulkCopy or EF Core Bulk Extensions). 3. Optimize: Disable Non-Clustered Indexes usage during
load, Rebuild after. 4. Transaction: Break into batches (Commit every 1000 rows) to avoid growing
Transaction Log too large. *** ## Q444. How do you find a Memory Leak in .NET Production?
Short Answer: 1. Capture: Take a Memory Dump (dotnet-dump collect). 2. Analyze: Open in
Visual Studio or WinDbg. 3. Inspect: Check “Dominator Graph” or Large Object Heap. 4. Common
Culprit: Static Lists growing forever, mismatched Event subscriptions (+= without -=), or un-disposed
Timers. *** ## Q445. High CPU usage in Production. How to debug?
Short Answer: 1. Tool: dotnet-counters or dotnet-trace. 2. Look for: High Garbage Collection (%
Time in GC). If > 30%, you have an allocation problem. 3. Thread Starvation: Check ThreadPool Queue
Length. *** ## Q446. Dictionary lookup is O(1). When does it become O(n)?
Short Answer: Hash Collisions. If many keys generate the same Hash Code, they fall into the same
bucket (Linked List). Lookup becomes linear scan of that bucket. Fix: Ensure custom objects implement a
good GetHashCode() that distributes values evenly. *** ## Q447. Explain “Backpressure” in a Message
Queue system.
Short Answer: When Consumers (WMS) strictly cannot keep up with Producers (Web Orders). Handling:
1. Reject: API returns 503 Overloaded. 2. Buffer: Queue fills up (risk of OOM). 3. Scale: Autoscaler
adds more Consumers. *** ## Q448. Distributed Transactions (Two-Phase Commit) vs Sagas?
Short Answer: * 2PC: Locks resources across DBs. Slow. Dangerous (Holds locks if coordinator crashes).
Avoid in Microservices. * Saga: Async. No global locks. Order Service commits -> Publishes Event ->
Inventory Service commits. If Inventory fails -> Publish “Refused” -> Order Service Compensates (Refunds).
*** ## Q449. Database Deadlock: Transaction A waits for B, B waits for A.
Short Answer: Prevention: 1. Consistent Ordering: Always access tables/rows in same order (Parent
then Child). 2. Short Transactions: Don’t do API calls inside a DB transaction. 3. Isolation Level:
Use ReadCommittedSnapshot (SQL Server) to avoid Reader/Writer blocking. *** ## Q450. Why use
IHostedService for standard background tasks?
Short Answer: It integrates with the App Lifecycle. Graceful Shutdown (StopAsync) allows you to finish
current work (save state) before the process is killed by K8s. *** ## Q451. What is the “Outbox Pattern”?
Short Answer: Guarantees “At Least Once” delivery of messages. Save “Order” and “OutboxMessage” in
same DB transaction. Worker process reads Outbox and pushes to RabbitMQ. If worker crashes, it retries
(Idempotency needed on receiver). *** ## Q452. Idempotent Consumer?
Short Answer: A receiver that can handle duplicate messages without error. Strategy: DB table
ProcessedMessageIds. IF EXISTS(MsgId) RETURN Success ELSE Process(). *** ## Q453. Dealing
with Slow 3rd Party APIs (e.g., FedEx)?
Short Answer: 1. Timeout: Set strict timeout (2s). Don’t hang threads forever. 2. Circuit Breaker:
If 50% fail, stop calling. Fail fast. 3. Async: Offload to background job. Don’t make user wait for label
46
generation. *** ## Q454. SQL: Clustered vs Non-Clustered Index?
Short Answer: * Clustered: Physically sorts data on disk. Only one per table (usually PK). The “Book
Content”. * Non-Clustered: Separate logical structure pointing to data. Many per table. The “Index at
back of book”. *** ## Q455. SQL: Covering Index?
Short Answer: Non-clustered index that includes (“Covers”) all columns requested in the SELECT. SQL
Server doesn’t need to look up the actual table row (Key Lookup). Huge performance win. *** ## Q456.
“Select N+1” in Microservices (HTTP)?
Short Answer: GetOrders() returns 100 IDs. Loop calls GetProduct(id) 100 times. Fix: Batching.
GetProducts(ids: [1,2,3. . . ]). Or Data Replication (Store basic Product data in Order DB). *** ## Q457.
What is “Tenant Isolation”?
Short Answer: Ensuring Customer A cannot see Customer B’s data. * Logicial: WHERE TenantId = X. *
Physical: Separate Database per Tenant. *** ## Q458. Handling Time Zones in Global WMS?
Short Answer: Rule: Backend, DB, Logs always use UTC. Display: Convert to Local Time ONLY at
the UI layer (Angular/React). Date: DateTimeOffset stores time + offset (+5:00), safer than DateTime.
*** ## Q459. Floating Point Arithmetic in Finance?
Short Answer: 0.1 + 0.2 != 0.3 (Double). Impact: Penny discrepancies in invoices. Fix: Always use
decimal. *** ## Q460. Immutable Infrastructure?
Short Answer: Never patch a running server. Build new Image -> Deploy -> Destroy old one. Prevents
“Configuration Drift”. *** ## Q461. Zero Trust Security?
Short Answer: Assume breach. Verify explicit permission for every request, even inside the private network.
(mTLS, JWT validation between microservices). *** ## Q462. What is “Chaos Engineering”?
Short Answer: Intentionally breaking things in Production (Netflix Simian Army). Tests resilience. “If I
kill the Redis Cache, does the site fall back to DB or crash?” *** ## Q463. Documentation Code?
Short Answer: Swagger (API), ADR (Architecture Decision Records). ADR: “We chose RabbitMQ
because. . . ” saved in Git. Prevents rehashing old arguments. *** ## Q464. Mentoring Juniors?
Situation: Junior writes massive if-else block. Action: Don’t just say “Fix it”. Teach Strategy Pattern.
Pair program the refactor. Explain the Why. *** ## Q465. Handling Conflict with Product Owner?
Situation: PO wants feature X causing technical debt. Action: Explain Risk (It will slow down future
features). Offer Options (Quick hack now + Refactor sprint later vs Do it right now). Let Business decide
based on cost. *** ## Q466. Production Outage Protocol?
1. Mitigate: Rollback or Flip Feature Flag. Restore service first.
2. Debug: Analyze logs/dumps offline.
3. RCA: Root Cause Analysis. Fix process, not just code. *** ## Q467. “It works on my machine”?
Short Answer: Unacceptable answer. Fix: Environments must match (Docker). Config must be externalized.
*** ## Q468. Bus Factor?
Short Answer: How many team members can get hit by a bus before the project dies? Goal: Increase
factor. Knowledge sharing, documentation, no “Hero Developers”. *** ## Q469. Trunk-Based Development?
Short Answer: Developers merge to Main daily. Requires robust Automated Tests and Feature Flags.
Avoids “Merge Hell” of long-lived branches. *** ## Q470. Database Migration Strategy?
Short Answer: Changes must be backward compatible. 1. Add Column (Nullable). 2. Deploy Code writing
to both. 3. Backfill data. 4. Deploy Code reading new. 5. Remove old column. *** ## Q471. Distributed
ID Generation?
Short Answer: Auto-increment (1, 2, 3) fails in distributed DB/Sharding (Collisions). Fix: UUID/GUID
(Random, but fragments Index), or Snowflake ID (Time + MachineID + Sequence) for sortable unique IDs.
*** ## Q472. Blob Storage vs Database?
47
Short Answer: * Database: Structured queries. Expensive. * Blob: Unstructured files (Images, PDFs).
Cheap. Pattern: Store Image in Blob, store URL in DB. *** ## Q473. CDN (Content Delivery Network)?
Short Answer: Caches static assets (JS, Images) on edge servers globally. Reduces latency for users and
load on origin server. *** ## Q474. WebSockets vs Server-Sent Events (SSE)?
Short Answer: * WebSockets: Bi-directional (Chat, Multiplayer game). * SSE: One-way Server->Client
(Stock ticker, Status update). Simpler over HTTP. *** ## Q475. Serialization: Private setters?
Short Answer: [Link] can deserialize to private setters using [JsonInclude] or generic con-
structor matching. Critical for Domain Models (Immutability). *** ## Q476. Value Objects (DDD)?
Short Answer: Object defined by its attributes, not ID. Address { Street, City }. Two addresses with
same values are Equal. Immutable. Validates itself on creation. *** ## Q477. Aggregate Root (DDD)?
Short Answer: Cluster of objects treated as a unit. Example: Order is Root. OrderItem is child. Rule:
You can only load/save the Root. You cannot load an OrderItem directly. Enforces consistency. *** ##
Q478. Anemic Domain Model (Anti-pattern)?
Short Answer: Classes with only Data (Getters/Setters). Logic is in Services. Rich Domain: Classes
contain logic ([Link]()). Preferred in DDD. *** ## Q479. Hexagonal Architecture?
Short Answer: Ports and Adapters. App logic in center. DB, UI, API are external “Adapters”. Allows
swapping DB without changing logic. *** ## Q480. Event Storming?
Short Answer: Workshop technique. Stakeholders put sticky notes on wall to map Domain Events (“Order
Placed”, “Shipped”). Derive Context Boundaries from the cluster. *** ## Q481. Competing Consumers
Pattern?
Short Answer: Multiple workers reading from same Queue. Load balances processing. Queue ensures a
message is delivered to only one consumer. *** ## Q482. Leaky Bucket Algorithm?
Short Answer: Rate Limiting. Requests fill bucket. Bucket leaks at constant rate. If full, requests overflow
(Rejected). *** ## Q483. Thundering Herd Problem?
Short Answer: Cache expires. 10,000 requests hit DB simultaneously to re-fetch same data. DB dies. Fix:
Cache Stampede Protection (Locking) or Probabilistic Early Expiration. *** ## Q484. Poison
Message?
Short Answer: Message that crashes the consumer constantly. Infinite loop of Retry -> Crash. Fix: Move
to Dead Letter Queue (DLQ) after N retries. Manual inspection. *** ## Q485. Polyglot Persistence?
Short Answer: Using best DB for job. SQL (Orders) + Mongo (Product Catalog) + Redis (Cache) +
Neo4j (Social Graph) in one system. *** ## Q486. Function as a Service (Serverless)?
Short Answer: Azure Functions / AWS Lambda. Event-driven. Scales to zero. Pay per execution. Risk:
Cold Starts. *** ## Q487. Cold Start?
Short Answer: Delay when Serverless function wakes up (loads Runtime) after inactivity. Fix: Premium
Plan (Pre-warmed instances) or Keep-Alive pings. *** ## Q488. What is IOptions<T>?
Short Answer: Pattern for strongly-typed configuration injection. IOptionsSnapshot (Reloads on change).
IOptionsMonitor (Event on change). *** ## Q489. [Link] Use Case?
Short Answer: Fast in-memory processing pipeline. Reader (Log Ingest) -> Channel -> Writer (Batch DB
Insert). *** ## Q490. Why prefer DateTimeOffset over DateTime?
Short Answer: DateTime is ambiguous (Does “10:00” mean UTC or Local?). DateTimeOffset is absolute
point in time relative to UTC. *** ## Q491. IEnumerable vs IReadOnlyList for API Returns?
Short Answer: Return IReadOnlyList or IEnumerable. Reason: Prevent consumer from performing
.Add() on the result. Express intent. *** ## Q492. How to secure a Microservice?
48
Short Answer: 1. Gateway: SSL Termination. 2. Auth: JWT validation. 3. Network: Private
VNET. No public IP. 4. Least Privilege: DB Connection string only has Sproc permissions. *** ## Q493.
Side-Effect in GET request?
Short Answer: GET should be safe (Idempotent). Do not change state (Update DB) in a GET. Use POST.
*** ## Q494. Richardson Maturity Model?
Short Answer: Levels of REST compliance. 0: POX (Plain Old XML). 1: Resources (/users). 2: Verbs
(GET/POST). 3: HATEOAS (Links). *** ## Q495. Grpc-Web?
Short Answer: Browsers cannot talk raw HTTP/2 gRPC. gRPC-Web is a proxy making it possible to call
gRPC from Angular/React. *** ## Q496. When to use SignalR?
Short Answer: Live Dashboards, Chat, Progress Bars, Notifications. Anytime “Refresh Button” is bad UX.
*** ## Q497. What is Blazor Server trade-off?
Short Answer: Pro: Instant load, full code on server. Con: Network latency for every click (SignalR).
Server memory per user (Circuit). Not for High latency / Offline apps. *** ## Q498. What is Blazor
WASM trade-off?
Short Answer: Pro: Runs offline, client CPU. Con: Large download size (DLLs). Slow initial load (without
AOT). *** ## Q499. Resume-Driven Development?
Short Answer: CV-Driven Development. Developer choosing tech (e.g., Kubernetes for a static blog) just to
learn it. Senior Role: Prevent this. Choose boring tech for critical systems. *** ## Q500. Final Question:
How do you stay current?
Short Answer: “I follow the .NET Blog, read Release Notes, subscribe to MS Learn, and build small POCs.
But I only adopt new tech in production after the ‘Hype Cycle’ settles to the ‘Plateau of Productivity’.” **
End of Guide*
49
The transition from the .NET Framework to .NET 5+ entails a significant architectural shift, especially in deploying enterprise applications. While .NET Framework relied on Windows-only environments with system-wide installations via the Global Assembly Cache (GAC), .NET 5+ offers cross-platform capabilities and side-by-side component deployment that eliminate DLL Hell. This shift requires re-platforming rather than a simple version upgrade, as enterprise applications must adapt from using IIS and AppDomains to more modern solutions like Kestrel and containerization. This architectural evolution enhances flexibility, performance, and scalability, crucial for modern enterprise environments .
Generic Attributes, introduced in C# 11, enhance code readability and safety by allowing attributes to accept type parameters directly rather than relying on the typeof() pattern. This change reduces verbosity and improves clarity by eliminating unnecessary code, making the developer's intent clearer. In complex applications where multiple attributes and types interact, Generic Attributes streamline code, reducing errors and simplifying maintenance while maintaining type safety, which is crucial for avoiding bugs in extensive and intricate codebases .
The removal of the Global Assembly Cache (GAC) in .NET Core has profoundly impacted DLL management and application deployment by allowing side-by-side installations and resolving issues related to "DLL Hell," where version conflicts could crash applications system-wide. Without the GAC, applications can independently include specific versions of dependencies, facilitating smoother deployments and updates. This change promotes greater modularity and reduces risks, as updates to shared libraries no longer affect multiple applications simultaneously, enhancing stability and simplifying dependency management .
Event storming is a collaborative workshop technique used in domain-driven design (DDD) to map out and explore domain events within a business process. It facilitates the identification of bounded contexts by allowing stakeholders to use sticky notes to chronologically display events across the system, highlighting relationships and dependencies among various parts. This visualization helps uncover the natural sub-domains, enabling architects to define clear boundary lines where each context operates autonomously but integrates with others through well-defined interfaces. The process promotes a shared understanding and helps teams converge on the ubiquitous language relevant to their domain .
Expression Trees in C# offer significant advantages over standard delegates by providing a data structure that represents code logic in a traversable, interpretable form. Unlike compiled delegates, Expression Trees can be inspected and modified at runtime, enabling scenarios such as dynamic query generation or translation into SQL by ORMs like Entity Framework. This feature enhances scenarios that require code as data, such as building LINQ queries that can be modified or inspected before execution, providing great flexibility and power in constructing complex data retrieval logic dynamically .
Blazor Server and Blazor WASM (WebAssembly) each have distinct trade-offs that influence architectural decisions. Blazor Server offers faster application load times and smaller app sizes, as the client only needs static resources, but it requires a persistent network connection for all user interactions, which can affect scalability under high latency or unreliable network conditions. Conversely, Blazor WASM allows the execution of compiled .NET code directly in the browser, offering offline availability and reduced server load, but results in larger initial downloads and slower startup times. These trade-offs dictate whether an application prioritizes fast interactions with frequent server communications or a richer client-side user experience .
The "Fail Fast" principle contributes to the reliability of software systems by ensuring that errors are detected and reported at the earliest possible stage, thereby minimizing potential damage. Implementation strategies include validating inputs immediately, throwing exceptions when invariants are violated, and employing assertions during development to catch errors early. This approach limits the propagation of errors, simplifies debugging, and prevents incorrect internal states from persisting. Adhering to this principle facilitates maintenance and enhances the overall robustness of the system .
Docker and Kubernetes offer substantial advantages in managing .NET Core applications within a microservices architecture. Docker simplifies the deployment process by encapsulating applications along with their dependencies into containers, ensuring consistency across development, testing, and production environments. This "Works on my machine" guarantee reduces deployment issues and increases reliability. Kubernetes complements this by orchestrating these containers at scale, managing load balancing, scaling, and recovery from failures through features like health checks and rolling updates. Together, they provide a robust framework for developing, deploying, and maintaining scalable and resilient microservices architectures .
The Single Responsibility Principle (SRP) dictates that a class should have only one reason to change, meaning it should have only one job or responsibility. This principle enhances code maintainability and scalability by making the codebase easier to understand, test, and modify. By confining a class to a single responsibility, any changes in the functionality will be limited to a specific class, thereby reducing the risk of introducing errors. Moreover, it promotes better code works by facilitating reusability and reducing dependency between various modules .
"Composition over Inheritance" is a design principle advocating for building systems using object composition rather than class inheritance. It is recommended in modular and scalable system design as it promotes flexibility by allowing parts of a system to be composed with different components at runtime, unlike inheritance which statically binds behavior. Composition leads to less tightly coupled designs, making code easier to maintain and extend without altering existing codebases. It allows developers to favor reuse over hierarchy, facilitating scalable, testable, and more adaptable architectures .