Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Sunday, September 7, 2025

Mastering C# Interviews: Top 150+ Essential Questions

 

Topic 1: C# Basics and Syntax

This section covers foundational elements like data types, operators, and control structures. Ideal for building core understanding.

Beginner Questions

  1. What is C# and how does it differ from C? C# is a modern, object-oriented language developed by Microsoft for .NET applications. Unlike C (procedural with manual memory management), C# offers automatic garbage collection via CLR and supports OOP. Scenario: In a real-life app like a banking system, C# simplifies error-prone tasks. Example: No pointers in safe mode reduce bugs. Analytical: Why might C#'s type safety prevent runtime errors in large-scale projects?
  2. Explain data types in C# with examples. Value types (int, float) store data directly; reference types (string, arrays) store references. Real-life: Use decimal for financial calculations to avoid floating-point errors. Code Example: int age = 25; decimal salary = 50000.50m; IQ Twist: If you add two shorts, what type is the result? (int, due to promotion.)
  3. What are operators in C#? Provide a scenario-based example. Arithmetic (+,-), relational (==,>), logical (&&,||). Scenario: In an e-commerce cart, use relational operators to check if total > discount threshold. Code: if (total > 100 && items >= 5) { ApplyDiscount(); } Informative: Overloading operators allows custom behaviors for user-defined types.
  4. How do you declare and initialize variables? Use type followed by name: string name = "John"; Real-life: In user registration, initialize variables for form data. Analytical: Why use var for type inference in complex queries?
  5. What is the difference between == and Equals() in C#? == checks reference equality for objects; Equals() checks value. Scenario: Comparing user IDs in a database query. Code: string a = "hi"; string b = new string("hi"); a == b; // true, but for custom classes, override Equals. IQ: When would == return false but Equals true?
  6. Explain loops in C# with a real-life example. for, while, do-while. Scenario: Processing daily sales data in a loop to calculate totals. Code: for(int i=0; i<sales.Length; i++) { total += sales[i]; } Analytical: How does foreach improve readability over for in collections?
  7. What are comments in C# and why are they important? Single-line (//), multi-line (/* */), XML (///). Real-life: Documenting code for team collaboration in enterprise software. Informative: XML comments generate documentation automatically.
  8. How does the if-else statement work? Give a scenario. Checks conditions for branching. Scenario: User authentication: if(password matches) login else error. Code: if(age >= 18) { Console.WriteLine("Adult"); } else { Console.WriteLine("Minor"); }
  9. What is the Main() method? Entry point of C# apps. Real-life: Starts console apps like command-line tools. Code: static void Main(string[] args) { } Analytical: Why is it static?
  10. Explain break and continue with examples. Break exits loop; continue skips iteration. Scenario: Skipping invalid data in file processing. Code: for(int i=1; i<=5; i++) { if(i==3) continue; Console.Write(i); } // Outputs 1245

Intermediate Questions

  1. What is namespace in C#? Groups related classes to avoid naming conflicts. Scenario: Organizing libraries in a multi-module app. Code: namespace MyApp { class Program { } } Analytical: How does using directive simplify code?
  2. Differentiate between const and readonly. Const: compile-time constant; readonly: runtime. Real-life: Const for fixed PI; readonly for config loaded at runtime. Code: const int Max = 100; readonly int Min; IQ: Can readonly be changed after constructor?
  3. What are nullable types? Provide a use case. Allow value types to be null: int? x = null; Scenario: Database fields that may be empty. Analytical: How does ?? operator handle nulls?
  4. Explain the using statement. Ensures resource disposal. Scenario: File handling to auto-close streams. Code: using(StreamReader sr = new StreamReader("file.txt")) { }
  5. What is the difference between int and Int32? Synonyms; int is alias for Int32. Informative: Use int for readability.

Expert Questions

  1. How does dynamic type work in C#? Bypasses compile-time checking. Scenario: Integrating with dynamic APIs like JSON. Code: dynamic obj = 5; obj = "hello"; Analytical: Trade-offs: flexibility vs type safety risks.
  2. Explain marshaling in C#. Converts managed to unmanaged types for interop. Scenario: Calling native DLLs in legacy systems. Code: Use [DllImport]. IQ: When to use explicit marshaling?
  3. What is the f suffix for floats? Denotes float literal: float f = 3.14f; Real-life: Precision in graphics rendering.

Topic 2: Object-Oriented Programming (OOP) in C#

Focuses on classes, inheritance, and polymorphism for modular code.

Beginner Questions

  1. What is a class and object? Class: blueprint; Object: instance. Scenario: Class Car; Object myCar = new Car(); Code: class Person { public string Name; }
  2. Explain inheritance. Child class inherits from parent. C# doesn't support multiple class inheritance. Real-life: Base Employee class for Manager subclass.
  3. What is encapsulation? Hiding internal details via access modifiers. Scenario: Private fields in a BankAccount class. Code: private int balance; public int GetBalance() { return balance; }
  4. Define abstraction. Showing essential features, hiding implementation. Scenario: Abstract Vehicle class with Drive() method. Code: abstract class Shape { public abstract void Draw(); }
  5. What is polymorphism? Same method, different behaviors (overload/override). Real-life: Draw() for Circle and Square.
  6. Explain constructors. Initialize objects. Default or parameterized. Code: class Person { public Person(string name) { Name = name; } }
  7. What are access modifiers? public, private, protected, internal. Scenario: Private for sensitive data.
  8. Differentiate struct and class. Struct: value type; Class: reference. Real-life: Struct for lightweight Point in graphics.
  9. What is a static class? Can't be instantiated; for utility methods. Code: static class MathUtils { public static int Add(int a, int b) { return a+b; } }
  10. Explain sealed class. Can't be inherited. Scenario: Final implementation in libraries.

Intermediate Questions

  1. What is method overloading? Same name, different parameters. Scenario: Add(int) and Add(double) in calculator. Code: int Add(int a, int b); double Add(double a, double b);
  2. Explain method overriding. Child redefines parent method with virtual/override. Scenario: Custom ToString() in subclasses.
  3. What is an interface? Contract for methods. Supports multiple inheritance. Code: interface IShape { void Draw(); }
  4. Differentiate abstract class and interface. Abstract: partial implementation; Interface: none. Analytical: When to use each in design patterns?
  5. What are partial classes? Split class across files. Real-life: Auto-generated code in designers.
  6. Explain extension methods. Add methods to existing types. Scenario: Add ToCurrency() to decimal. Code: public static string ToCurrency(this decimal val) { return val.ToString("C"); }
  7. What is this keyword? Refers to current instance. Scenario: Differentiate fields and params.

Expert Questions

  1. Explain covariance and contravariance. Covariance: return derived types; Contravariance: accept base types in delegates. Scenario: Generic interfaces like IEnumerable<out t="">.</out>
  2. What is composition vs aggregation? Composition: owns parts (strong); Aggregation: references (weak). Real-life: Car owns Engine (composition); Car has Driver (aggregation).
  3. How to implement private constructors? For singletons. Code: private Singleton() { } public static Singleton Instance { get; }
  4. Explain duck typing in C#. Achieved via dynamic; focus on methods, not types. Scenario: Runtime plugin loading.
  5. What are custom attributes? Metadata for code. Code: [Obsolete] public void OldMethod() { }

Topic 3: Collections and Data Structures

Handling data efficiently with arrays, lists, etc.

Beginner Questions

  1. What is an array? Fixed-size collection. Code: int[] nums = {1,2,3};
  2. Explain jagged arrays. Array of arrays. Scenario: Irregular matrix data. Code: int[][] jag = new int[3][];
  3. What is ArrayList? Dynamic array for objects. Real-life: Growing shopping cart.
  4. Differentiate Array and ArrayList. Array: fixed, typed; ArrayList: dynamic, untyped.
  5. What is List<t>?</t> Generic dynamic list. Code: List<int> nums = new List<int>(); nums.Add(1);
  6. Explain Dictionary in C#. Key-value pairs. Scenario: User ID to Name mapping. Code: Dictionary<int, string> dict = new Dictionary<int, string>();
  7. What is BitArray? Compact bool array. Real-life: Flag settings.
  8. Explain IEnumerable. For iteration. Scenario: Custom collections.
  9. What is a stack? LIFO collection. Code: Stack<int> s = new Stack<int>(); s.Push(1);
  10. What is a queue? FIFO. Scenario: Task processing.

Intermediate Questions

  1. Differentiate List<t> and array.</t> List dynamic; array fixed.
  2. What is HashSet? Unique elements. Scenario: Deduplicating data.
  3. Explain concurrent collections. Thread-safe, like ConcurrentDictionary. Real-life: Multi-threaded apps.
  4. What is IQueryable vs IEnumerable? IQueryable for deferred DB queries; IEnumerable in-memory.
  5. How to use params array? Variable args. Code: int Sum(params int[] nums) { }

Expert Questions

  1. Explain ArraySegment for memory efficiency. Views array portion without copying. Scenario: Large data processing.
  2. What are weak references? Allow GC to collect if needed. Scenario: Caching.
  3. How to handle large datasets with yield? Lazy enumeration. Code: IEnumerable<int> GetNums() { yield return 1; }
  4. Explain Tuple and ValueTuple. Group data. Code: (int, string) t = (1, "hi");
  5. What is SortedList? Sorted key-value.

Topic 4: Exception Handling and Debugging

Managing errors gracefully.

Beginner Questions

  1. What is an exception? Runtime error. Scenario: Divide by zero.
  2. Explain try-catch-finally. Try: code; Catch: handle; Finally: cleanup. Code: try { int x=1/0; } catch(Exception e) { } finally { }
  3. What is throw? Raise custom exception.
  4. Differentiate Exception and Error. Exception: recoverable; Error: system-level.
  5. What are custom exceptions? Derive from Exception. Scenario: Business rules.

Intermediate Questions

  1. Explain multiple catch blocks. Specific to general. Code: catch(DivideByZeroException) { } catch(Exception) { }
  2. What is inner exception? Wrapped exception for chaining.
  3. How to log exceptions? Use libraries like NLog.
  4. Explain stack trace. Call history for debugging.
  5. What is the using statement for exceptions? Auto-dispose IDisposable.

Expert Questions

  1. How to handle async exceptions? Use try-catch in async methods.
  2. Explain AggregateException. For multiple task errors.
  3. What is exception filters? Catch if condition: catch(Exception e) when (e.Message.Contains("error"))
  4. How to use global exception handling? AppDomain.UnhandledException event.
  5. Analytical: Design a retry mechanism for exceptions. Use loop with try-catch and delay.

Topic 5: Delegates, Events, and LINQ

Advanced functional features.

Beginner Questions

  1. What is a delegate? Function pointer. Code: delegate int Calc(int a, int b);
  2. Explain events. Publisher-subscriber. Scenario: Button click.
  3. What is LINQ? Query language for data. Code: var q = from x in list where x>10 select x;
  4. Explain Func, Action, Predicate. Func: returns; Action: void; Predicate: bool.
  5. What is lambda expression? Anonymous function: x => x*2

Intermediate Questions

  1. Differentiate delegate and method. Delegate holds reference.
  2. How to use multicast delegates? += multiple methods.
  3. Explain LINQ to SQL. Queries databases.
  4. What is deferred execution in LINQ? Query runs on enumeration.
  5. How to join in LINQ? Code: from e in emp join d in dept on e.DeptId equals d.Id

Expert Questions

  1. Explain covariance in delegates. Return derived types.
  2. What is PLINQ? Parallel LINQ for performance.
  3. How to create custom LINQ providers? Implement IQueryable.
  4. Analytical: When to use events vs delegates? Events for encapsulation.
  5. Scenario: Implement event for stock price change. Raise when price fluctuates.

Topic 6: Multithreading and Asynchronous Programming

Handling concurrency.

Beginner Questions

  1. What is a thread? Execution unit. Scenario: Background tasks.
  2. Explain Task. Represents async operation.
  3. What is async/await? Simplifies async code. Code: async Task DoWork() { await Task.Delay(1000); }
  4. Differentiate Thread and Task. Task: higher-level abstraction.
  5. What is lock statement? Ensures single-thread access.

Intermediate Questions

  1. Explain ThreadPool. Manages threads efficiently.
  2. What is deadlock? Threads waiting forever. Analytical: Prevention strategies.
  3. How to use Parallel.ForEach? Parallel loop.
  4. Explain CancellationToken. Cancel tasks.
  5. What is ConfigureAwait? Avoids context capture.

Expert Questions

  1. Explain TPL (Task Parallel Library). For parallelism.
  2. How to handle concurrency in collections? ConcurrentBag, etc.
  3. What is ValueTask? Efficient async return.
  4. Scenario: Implement producer-consumer with channels. Use System.Threading.Channels.
  5. Analytical: Race conditions in async code. Use locks or atomics.

Topic 7: Memory Management and Advanced Concepts

Garbage collection, reflection, etc.

Beginner Questions

  1. What is Garbage Collection (GC)? Auto-frees memory.
  2. Explain managed vs unmanaged code. Managed: CLR; Unmanaged: native.
  3. What is stack and heap? Stack: value types; Heap: references.
  4. Explain Boxing and Unboxing. Value to reference and vice versa.
  5. What is Reflection? Runtime type inspection.

Intermediate Questions

  1. How does GC work? Generations? Gen0-2 for efficiency.
  2. Explain Dispose and Finalize. Dispose: manual; Finalize: GC.
  3. What is unsafe code? Pointers allowed.
  4. Explain String vs StringBuilder. String immutable; StringBuilder mutable.
  5. What are generics? Type-safe templates. Code: List<T>

Expert Questions

  1. Explain weak references usage. For non-critical caching.
  2. What is Roslyn? Compiler platform.
  3. How to use stackalloc? Stack allocation for perf.
  4. Explain local functions. Methods inside methods.
  5. Analytical: Memory leaks in C#. Causes: events, statics.

Topic 8: File Handling and Serialization

Working with external data.

Beginner Questions

  1. What is StreamReader/Writer? Read/write files.
  2. Explain serialization. Object to stream. Scenario: Saving state.
  3. What is JSON serialization? Use JsonSerializer.
  4. How to read a file? Code: string text = File.ReadAllText("file.txt");
  5. What is BinaryFormatter? Binary serialization.

Intermediate Questions

  1. Differentiate XML and JSON serialization. XML: verbose; JSON: lightweight.
  2. How to handle large files? Stream processing.
  3. Explain FileStream. Byte-level access.
  4. What is Path class? Manipulates paths.
  5. Scenario: Log errors to file. Append with StreamWriter.

Expert Questions

  1. Explain memory-mapped files. Efficient large data.
  2. How to secure serialization? Use secure formats.
  3. Analytical: Performance in file I/O. Buffering strategies.
  4. What is isolated storage? Sandboxed file access.
  5. Scenario: Asynchronous file reading. Use File.ReadAllTextAsync.

Topic 9: .NET Framework and CLR

Core runtime concepts.

Beginner Questions

  1. What is CLR? Executes managed code.
  2. Explain JIT compiler. Compiles IL to native.
  3. What is assembly? Compiled code unit.
  4. Differentiate .NET Framework and .NET Core. Core: cross-platform.
  5. What is IL/MSIL? Intermediate Language.

Intermediate Questions

  1. Explain AppDomain. Isolation boundary.
  2. What is metadata in assemblies? Type info.
  3. How to sign assemblies? Strong naming.
  4. Explain GAC. Global Assembly Cache.
  5. Scenario: Versioning in assemblies. Handle conflicts.

Expert Questions

  1. What is Source Generators? Compile-time code gen.
  2. Explain AOT compilation. Ahead-of-time.
  3. Analytical: CLR security models. Code access security.
  4. How to interop with COM? Use ComVisible.
  5. Scenario: Custom runtime hosting. Embed CLR in apps.
  6. Bonus: What is ref local variables? Reference to variables.
  7. Bonus: Explain pattern matching. Switch on types.
  8. Bonus: What are records? Immutable data classes.

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam

Post Bottom Ad

Responsive Ads Here