Skip to main content

Infosys top 50 .net Interview Questions and Answers in details

.Net Core & CLR

1. What is .NET, and how does the CLR work?
.NET is a developer platform from Microsoft providing a runtime (CLR), base class libraries, and tools to build apps for web, desktop, mobile, cloud, and more.

The CLR (Common Language Runtime) manages code execution (MSIL), memory allocation, garbage collection, type safety, and exception handling, enabling multiple languages (C#, F#, VB) to run on the same runtime.

2. What are assemblies in .NET?
An assembly is the basic unit of deployment and versioning, typically a DLL or EXE containing IL code, metadata, and resources.

Assemblies can be private (application-local) or shared (in the Global Assembly Cache, typically strong-named).
[1]

3. Difference between value types and reference types.
Value types (struct, int, bool) are allocated typically on the stack or inline in objects, store the actual data, and are copied by value.

Reference types (class, array, string) live on the heap, variables store references (pointers) to data, and assignments copy the reference, not the object.

4. What is boxing and unboxing?
Boxing converts a value type to a reference type by wrapping it in an object on the managed heap (e.g.,
object o = 5;).
Unboxing extracts the value type from the object (e.g.,
int x = (int)o;), which is more expensive and may throw InvalidCastException if types mismatch.

5. What are the four pillars of OOP in C#?
The four pillars are Encapsulation, Inheritance, Polymorphism, and Abstraction.

They enable organizing code into reusable, maintainable objects by hiding details, reusing behavior, and varying implementations behind common interfaces.

6. Abstract class vs interface in C#.
An abstract class can have fields, constructors, implemented and abstract methods, and is used when types share a common base with some default behavior.

An interface defines only contracts (methods/properties/events) with no fields or implementation (till default interface methods in newer C#), ideal for multiple inheritance of behavior.

7. Method overloading vs overriding.
Overloading: same method name, different parameter lists in the same class; decided at compile time.

Overriding: derived class provides a new implementation of a
virtual/abstract method in base class using override; resolved at runtime (polymorphism).

8. ref, out, and in parameters.
ref requires the variable to be initialized before passing; allows reading and modifying inside the method.
out does not require initialization; must be assigned inside the method; used for returning multiple values.
in is a read-only by-reference parameter, preventing modification in the called method.

9. What is the using statement in C#?
using ensures deterministic disposal of objects implementing IDisposable, wrapping them in a try/finally block that calls Dispose().
It is commonly used for resources like
SqlConnection, FileStream, etc., to avoid resource leaks.

10. What is a delegate and an event?
A delegate is a type-safe function pointer that can reference one or more methods with a specific signature.

An event wraps a delegate to provide a publisher–subscriber pattern, allowing clients to subscribe/unsubscribe but not invoke the delegate directly.

11–20: Memory, GC, and Async

11. How does garbage collection work in .NET?
The GC automatically frees memory for objects that are no longer reachable, using generations (0, 1, 2) to optimize collection frequency.

It compacts memory to reduce fragmentation and runs finalizers (if present) before reclaiming objects marked for collection.

12. IDisposable vs finalizer (~ClassName).
IDisposable.Dispose() is for deterministic resource cleanup, called explicitly or via using.
Finalizers are non-deterministic, called by GC before object reclamation, and should only be used when necessary because they delay collection and add overhead.

13. What is a WeakReference and when to use it?
WeakReference allows the GC to collect an object even if a reference exists, avoiding memory leaks in caching scenarios.
It is useful when you want to cache objects but do not want them to prevent garbage collection when memory is needed.

14. Explain async/await in C#.
async marks a method that contains asynchronous operations and can use await on Task/Task<T> returning methods.
await asynchronously waits without blocking the thread, resuming execution after the awaited operation completes, improving scalability for IO-bound workloads.

15. Task vs Thread.
A
Thread is a low-level OS construct representing a unit of execution; managing many threads directly is expensive.
A
Task represents a higher-level unit of work that runs on the thread pool, enabling easier composition, cancellation, and continuation patterns.

16. Synchronous vs asynchronous calls in web apps.
Synchronous calls block the thread until completion, limiting scalability, especially during IO waits.

Asynchronous calls free up the request thread while waiting (e.g., DB, API), allowing the server to serve more concurrent requests with the same resources.

17. What is thread safety and how to ensure it?
Thread safety means code can safely execute concurrently without race conditions or inconsistent state.

It can be achieved via locks (
lock), concurrent collections, immutability, or synchronization primitives like SemaphoreSlim and Monitor.

18. What are ConcurrentDictionary and BlockingCollection?
ConcurrentDictionary provides a thread-safe dictionary with atomic operations like GetOrAdd and TryUpdate.
BlockingCollection is a thread-safe producer–consumer collection that supports blocking and bounding.

19. What is ConfigureAwait(false)?
ConfigureAwait(false) tells the awaited task not to capture the current synchronization context, resuming on a thread pool thread instead.
It is useful in library code to avoid deadlocks and slightly improve performance without needing to marshal back to a specific context.

20. What is a deadlock, and how can it occur with async?
A deadlock is a situation where two or more operations wait indefinitely for each other to release resources.

In async code, deadlocks often occur when synchronously blocking on async calls (e.g.,
.Result, .Wait() on the main thread) while the continuation needs that context.

21–30: ASP.NET Core / Web API

21. What is middleware in ASP.NET Core?
Middleware is a component in the HTTP request pipeline that can inspect, modify, or short-circuit requests and responses.

Middleware components execute in order of registration in
Program.cs/Startup.cs, forming a pipeline via next().

22. Describe the ASP.NET Core request pipeline.
The pipeline starts from the server (Kestrel/IIS), passes the request through registered middleware (routing, authentication, authorization, MVC), and ends by generating a response.

Each middleware can perform pre-processing, call the next delegate, and perform post-processing after the next middleware completes.

23. What is dependency injection (DI) in ASP.NET Core and how is it implemented?
DI is a pattern where dependencies are provided to a class rather than created inside it, improving testability and decoupling.

ASP.NET Core has a built-in IoC container; services are registered in the service collection (AddSingleton, AddScoped, AddTransient) and injected via constructors.

24. appsettings.json usage and configuration binding.
appsettings.json stores configuration such as connection strings, logging levels, and app-specific settings.

Configuration is loaded at startup and can be bound to strongly typed POCO classes using `services.Configure<T>` and `IOptions<T>`.

25. Difference between IActionResult and ActionResult<T>.
IActionResult represents a non-generic result (e.g., Ok(), BadRequest()), giving flexibility but no compile-time type info for response bodies.
ActionResult<T> combines a return type T with standardized HTTP results, enabling better swagger/metadata and strong typing.

26. GET vs POST vs PUT vs DELETE in Web APIs.
GET retrieves data and should be idempotent and side-effect free.

POST creates resources or triggers operations; PUT replaces a resource; DELETE removes a resource, all forming RESTful semantics.

27. How do you secure an ASP.NET Core API (JWT)?
Use authentication middleware with JWT Bearer scheme, validating tokens issued by an identity provider.

Configure authorization policies/attributes (
[Authorize], roles, policies), and store secrets securely (Key Vault, user secrets) rather than in source code.

28. What is CORS and how is it configured?
CORS (Cross-Origin Resource Sharing) defines how a browser permits a web app from one origin to access resources from another origin.

In
ASP.NET Core, configure CORS policies via services.AddCors and app.UseCors, specifying allowed origins, headers, and methods.

29. Difference between TempData, ViewData, and ViewBag (MVC).
ViewData is a dictionary (ViewDataDictionary) for passing data from controller to view, using string keys.
ViewBag is a dynamic wrapper around ViewData for more natural syntax, while TempData uses session-backed storage to survive one redirect.

30. What is a partial view and when to use it?
A partial view is a reusable view fragment rendered within other views (e.g., header, footer, widgets).

It promotes DRY and modular UI design, improving maintainability and reuse.

31–40: Entity Framework Core & SQL

31. What is Entity Framework Core, and what are its advantages?
EF Core is an ORM that allows working with databases using .NET objects instead of raw SQL, supporting LINQ queries and change tracking.

Advantages include faster development, maintainable code, provider independence, and built-in migrations.

32. Code First vs Database First in EF.
Code First: model classes define the schema, and EF generates/migrates the database from code.

Database First: the database exists first, and EF generates models and context from it.

33. What is change tracking in EF Core?
Change tracking monitors entity states (Added, Modified, Deleted, Unchanged) in the context.

On
SaveChanges, EF translates these states into proper SQL INSERT, UPDATE, and DELETE commands.

34. Lazy loading vs eager loading vs explicit loading.
Lazy loading automatically loads related entities when navigation properties are accessed, potentially causing N+1 queries.

Eager loading uses
.Include()/.ThenInclude() to load related data in a single query, while explicit loading uses methods like Entry(...).Collection(...).Load().

35. How do you optimize EF Core queries?
Use projection (
Select) to fetch only required columns, and use eager loading judiciously.
Avoid chatty N+1 patterns, use
AsNoTracking for read-only queries, and ensure proper indexing at the database level.

36. Write a SQL query to find the second highest salary.
One common pattern is:
SELECT MAX(Salary) FROM Employee WHERE Salary < (SELECT MAX(Salary) FROM Employee);.
Alternatively, use
ROW_NUMBER() or DENSE_RANK() window functions ordered by salary descending.

37. Difference between INNER JOIN, LEFT JOIN, and FULL JOIN.
INNER JOIN returns only matching rows between tables.

LEFT JOIN returns all rows from the left table plus matching rows from the right, while FULL JOIN returns all rows from both sides, matching where possible.

38. What are indexes, and how do they impact performance?
Indexes are data structures (often B-trees) that speed up lookups and sorting by providing fast access paths to rows.

They improve read performance but can slow down writes (INSERT/UPDATE/DELETE) and consume additional storage, so they must be designed carefully.

39. How do you optimize a slow stored procedure?
Analyze execution plan, add or adjust indexes, and avoid unnecessary cursor or row-by-row processing.

Refactor complex logic, reduce repeated subqueries, parameterize properly, and ensure statistics are up to date.

40. Transaction vs lock in SQL Server.
A transaction is a logical unit of work that must be committed or rolled back as a whole, ensuring ACID properties.

Locks are low-level mechanisms used by the database to maintain isolation and consistency during transactions, controlling concurrent access to data.

41–50: .NET Core vs Framework, Design & Angular

41. Difference between .NET Framework and .NET Core/.NET 6+.
.NET Framework is Windows-only and primarily for legacy desktop/web (
ASP.NET) apps, with limited cross-platform support.
.NET Core/.NET (5+) is cross-platform, modular, high-performance, and the future direction with unified platform and improved tooling.

42. What is Kestrel in ASP.NET Core?
Kestrel is the cross-platform web server used by
ASP.NET Core to handle HTTP requests.
On Windows it often runs behind IIS as a reverse proxy; on Linux it commonly runs behind Nginx or Apache.

43. Explain the Repository and Unit of Work patterns.
Repository encapsulates data access logic, providing a collection-like interface for domain entities.

Unit of Work coordinates changes across multiple repositories, managing a single transaction boundary, typically wrapping EF
DbContext.

44. What is dependency inversion, and how is it applied with DI containers?
Dependency Inversion (from SOLID) states that high-level modules should depend on abstractions, not concretions.

DI containers implement this by resolving interfaces to concrete implementations at runtime, decoupling modules and enabling easier testing.

45. Common design patterns used in .NET applications.
Frequently used patterns include Singleton, Factory, Strategy, Repository, Unit of Work, and Dependency Injection.

In web apps, MVC and CQRS/mediator (e.g., MediatR) are also common to separate concerns and manage complexity.

46. How do you handle configuration per environment (Dev/Test/Prod) in ASP.NET Core?
Use environment-specific JSON files (
appsettings.Development.json, etc.) loaded based on ASPNETCORE_ENVIRONMENT.
Combine with secrets storage (User Secrets, Key Vault, environment variables) for sensitive config and override precedence.

47. What is logging in ASP.NET Core, and which providers can you use?
ASP.NET Core’s logging abstraction supports structured logging with categories and log levels via ILogger<T>.
Providers include Console, Debug, EventSource, Azure Application Insights, and third-party providers like Serilog, NLog, or Seq.

48. Difference between constructor and ngOnInit in Angular.
The constructor is a TypeScript feature for dependency injection and simple initialization, executed when the component instance is created.

ngOnInit is an Angular lifecycle hook called once after Angular initializes input-bound properties, ideal for fetching data/initialization logic that depends on bindings.

49. Types of data binding in Angular.
Angular supports interpolation (
{{}}), property binding ([property]), event binding ((event)), and two-way binding ([(ngModel)]).
These binding forms connect the component class and template, enabling unidirectional or bidirectional data flow.

50. What is lazy loading in Angular and why use it in a full-stack .NET app?
Lazy loading loads feature modules on demand when their routes are visited instead of at initial application bootstrap.

It reduces initial bundle size and improves first-load performance, especially for large enterprise apps built with
ASP.NET Core backends and Angular frontends.

Comments

Popular posts from this blog

Top 30 Tricky C# Coding Interview Questions (With Solutions)

  1. Reverse a String Without Built-in Methods Q: Write a C# method to reverse a string without using built-in reverse functions. A: string Reverse(string input) {     char[] result = new char[input.Length];     for (int i = 0; i < input.Length; i++)         result[i] = input[input.Length - 1 - i];     return new string(result); } 2. Find Duplicates in an Integer Array Q: Detect and print duplicates in an integer array. A: void FindDuplicates(int[] arr) {     var seen = new HashSet<int>();     foreach (int num in arr) {         if (seen.Contains(num))             Console.WriteLine("Duplicate: " + num);         else             seen.Add(num);   ...

Cracking the Code: Your Guide to the Top 60 C# Interview Questions

So, you're gearing up for a C# interview? Fantastic! This powerful and versatile language is a cornerstone of modern software development, and landing that C# role can open up a world of exciting opportunities. But navigating the interview process can feel like traversing a complex codebase. Fear not! We've compiled a comprehensive list of the top 60 C# interview questions, complete with detailed answers, to help you ace your next technical challenge. Whether you're just starting your C# journey or you're a seasoned pro looking to brush up your knowledge, this guide has something for you. We've broken down the questions into three levels: Beginner, Intermediate, and Advanced, allowing you to focus on the areas most relevant to your experience. Let's dive in and equip you with the knowledge you need to shine! Beginner Level (1–20) 1. What is C#? C# is a modern, object-oriented programming language developed by Microsoft as part of its .NET platform. It is design...

Ace Your .NET Core Coding Interview: Top 20 Algorithmic & Problem-Solving Questions

 Beyond knowing the ins and outs of .NET Core, a successful technical interview often hinges on your ability to solve fundamental coding problems. These questions test your logical thinking, algorithm design, and grasp of basic data structures. This blog post provides 20 essential coding interview questions, complete with explanations and example approaches in C#, to help you shine in your next .NET Core technical assessment. 1. Reverse a String Without Built-in Functions Explanation: A classic that tests your understanding of loops and string manipulation. Question: Write a C# method to reverse a given string without using built-in Reverse() or ToArray() methods. Answer: C# public string ReverseString ( string input ) { if ( string .IsNullOrEmpty(input)) { return input; } char [] charArray = input.ToCharArray(); int left = 0 ; int right = charArray.Length - 1 ; while (left < right) { // Swap characters char...