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
- 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?
- 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.)
- 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.
- 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?
- 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?
- 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?
- 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.
- 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"); }
- 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?
- 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
- 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?
- 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?
- 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?
- Explain the using statement. Ensures resource disposal. Scenario: File handling to auto-close streams. Code: using(StreamReader sr = new StreamReader("file.txt")) { }
- What is the difference between int and Int32? Synonyms; int is alias for Int32. Informative: Use int for readability.
Expert Questions
- 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.
- 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?
- 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
- What is a class and object? Class: blueprint; Object: instance. Scenario: Class Car; Object myCar = new Car(); Code: class Person { public string Name; }
- Explain inheritance. Child class inherits from parent. C# doesn't support multiple class inheritance. Real-life: Base Employee class for Manager subclass.
- 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; }
- Define abstraction. Showing essential features, hiding implementation. Scenario: Abstract Vehicle class with Drive() method. Code: abstract class Shape { public abstract void Draw(); }
- What is polymorphism? Same method, different behaviors (overload/override). Real-life: Draw() for Circle and Square.
- Explain constructors. Initialize objects. Default or parameterized. Code: class Person { public Person(string name) { Name = name; } }
- What are access modifiers? public, private, protected, internal. Scenario: Private for sensitive data.
- Differentiate struct and class. Struct: value type; Class: reference. Real-life: Struct for lightweight Point in graphics.
- 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; } }
- Explain sealed class. Can't be inherited. Scenario: Final implementation in libraries.
Intermediate Questions
- 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);
- Explain method overriding. Child redefines parent method with virtual/override. Scenario: Custom ToString() in subclasses.
- What is an interface? Contract for methods. Supports multiple inheritance. Code: interface IShape { void Draw(); }
- Differentiate abstract class and interface. Abstract: partial implementation; Interface: none. Analytical: When to use each in design patterns?
- What are partial classes? Split class across files. Real-life: Auto-generated code in designers.
- 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"); }
- What is this keyword? Refers to current instance. Scenario: Differentiate fields and params.
Expert Questions
- Explain covariance and contravariance. Covariance: return derived types; Contravariance: accept base types in delegates. Scenario: Generic interfaces like IEnumerable<out t="">.</out>
- What is composition vs aggregation? Composition: owns parts (strong); Aggregation: references (weak). Real-life: Car owns Engine (composition); Car has Driver (aggregation).
- How to implement private constructors? For singletons. Code: private Singleton() { } public static Singleton Instance { get; }
- Explain duck typing in C#. Achieved via dynamic; focus on methods, not types. Scenario: Runtime plugin loading.
- 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
- What is an array? Fixed-size collection. Code: int[] nums = {1,2,3};
- Explain jagged arrays. Array of arrays. Scenario: Irregular matrix data. Code: int[][] jag = new int[3][];
- What is ArrayList? Dynamic array for objects. Real-life: Growing shopping cart.
- Differentiate Array and ArrayList. Array: fixed, typed; ArrayList: dynamic, untyped.
- What is List<t>?</t> Generic dynamic list. Code: List<int> nums = new List<int>(); nums.Add(1);
- Explain Dictionary in C#. Key-value pairs. Scenario: User ID to Name mapping. Code: Dictionary<int, string> dict = new Dictionary<int, string>();
- What is BitArray? Compact bool array. Real-life: Flag settings.
- Explain IEnumerable. For iteration. Scenario: Custom collections.
- What is a stack? LIFO collection. Code: Stack<int> s = new Stack<int>(); s.Push(1);
- What is a queue? FIFO. Scenario: Task processing.
Intermediate Questions
- Differentiate List<t> and array.</t> List dynamic; array fixed.
- What is HashSet? Unique elements. Scenario: Deduplicating data.
- Explain concurrent collections. Thread-safe, like ConcurrentDictionary. Real-life: Multi-threaded apps.
- What is IQueryable vs IEnumerable? IQueryable for deferred DB queries; IEnumerable in-memory.
- How to use params array? Variable args. Code: int Sum(params int[] nums) { }
Expert Questions
- Explain ArraySegment for memory efficiency. Views array portion without copying. Scenario: Large data processing.
- What are weak references? Allow GC to collect if needed. Scenario: Caching.
- How to handle large datasets with yield? Lazy enumeration. Code: IEnumerable<int> GetNums() { yield return 1; }
- Explain Tuple and ValueTuple. Group data. Code: (int, string) t = (1, "hi");
- What is SortedList? Sorted key-value.
Topic 4: Exception Handling and Debugging
Managing errors gracefully.
Beginner Questions
- What is an exception? Runtime error. Scenario: Divide by zero.
- Explain try-catch-finally. Try: code; Catch: handle; Finally: cleanup. Code: try { int x=1/0; } catch(Exception e) { } finally { }
- What is throw? Raise custom exception.
- Differentiate Exception and Error. Exception: recoverable; Error: system-level.
- What are custom exceptions? Derive from Exception. Scenario: Business rules.
Intermediate Questions
- Explain multiple catch blocks. Specific to general. Code: catch(DivideByZeroException) { } catch(Exception) { }
- What is inner exception? Wrapped exception for chaining.
- How to log exceptions? Use libraries like NLog.
- Explain stack trace. Call history for debugging.
- What is the using statement for exceptions? Auto-dispose IDisposable.
Expert Questions
- How to handle async exceptions? Use try-catch in async methods.
- Explain AggregateException. For multiple task errors.
- What is exception filters? Catch if condition: catch(Exception e) when (e.Message.Contains("error"))
- How to use global exception handling? AppDomain.UnhandledException event.
- 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
- What is a delegate? Function pointer. Code: delegate int Calc(int a, int b);
- Explain events. Publisher-subscriber. Scenario: Button click.
- What is LINQ? Query language for data. Code: var q = from x in list where x>10 select x;
- Explain Func, Action, Predicate. Func: returns; Action: void; Predicate: bool.
- What is lambda expression? Anonymous function: x => x*2
Intermediate Questions
- Differentiate delegate and method. Delegate holds reference.
- How to use multicast delegates? += multiple methods.
- Explain LINQ to SQL. Queries databases.
- What is deferred execution in LINQ? Query runs on enumeration.
- How to join in LINQ? Code: from e in emp join d in dept on e.DeptId equals d.Id
Expert Questions
- Explain covariance in delegates. Return derived types.
- What is PLINQ? Parallel LINQ for performance.
- How to create custom LINQ providers? Implement IQueryable.
- Analytical: When to use events vs delegates? Events for encapsulation.
- Scenario: Implement event for stock price change. Raise when price fluctuates.
Topic 6: Multithreading and Asynchronous Programming
Handling concurrency.
Beginner Questions
- What is a thread? Execution unit. Scenario: Background tasks.
- Explain Task. Represents async operation.
- What is async/await? Simplifies async code. Code: async Task DoWork() { await Task.Delay(1000); }
- Differentiate Thread and Task. Task: higher-level abstraction.
- What is lock statement? Ensures single-thread access.
Intermediate Questions
- Explain ThreadPool. Manages threads efficiently.
- What is deadlock? Threads waiting forever. Analytical: Prevention strategies.
- How to use Parallel.ForEach? Parallel loop.
- Explain CancellationToken. Cancel tasks.
- What is ConfigureAwait? Avoids context capture.
Expert Questions
- Explain TPL (Task Parallel Library). For parallelism.
- How to handle concurrency in collections? ConcurrentBag, etc.
- What is ValueTask? Efficient async return.
- Scenario: Implement producer-consumer with channels. Use System.Threading.Channels.
- Analytical: Race conditions in async code. Use locks or atomics.
Topic 7: Memory Management and Advanced Concepts
Garbage collection, reflection, etc.
Beginner Questions
- What is Garbage Collection (GC)? Auto-frees memory.
- Explain managed vs unmanaged code. Managed: CLR; Unmanaged: native.
- What is stack and heap? Stack: value types; Heap: references.
- Explain Boxing and Unboxing. Value to reference and vice versa.
- What is Reflection? Runtime type inspection.
Intermediate Questions
- How does GC work? Generations? Gen0-2 for efficiency.
- Explain Dispose and Finalize. Dispose: manual; Finalize: GC.
- What is unsafe code? Pointers allowed.
- Explain String vs StringBuilder. String immutable; StringBuilder mutable.
- What are generics? Type-safe templates. Code: List<T>
Expert Questions
- Explain weak references usage. For non-critical caching.
- What is Roslyn? Compiler platform.
- How to use stackalloc? Stack allocation for perf.
- Explain local functions. Methods inside methods.
- Analytical: Memory leaks in C#. Causes: events, statics.
Topic 8: File Handling and Serialization
Working with external data.
Beginner Questions
- What is StreamReader/Writer? Read/write files.
- Explain serialization. Object to stream. Scenario: Saving state.
- What is JSON serialization? Use JsonSerializer.
- How to read a file? Code: string text = File.ReadAllText("file.txt");
- What is BinaryFormatter? Binary serialization.
Intermediate Questions
- Differentiate XML and JSON serialization. XML: verbose; JSON: lightweight.
- How to handle large files? Stream processing.
- Explain FileStream. Byte-level access.
- What is Path class? Manipulates paths.
- Scenario: Log errors to file. Append with StreamWriter.
Expert Questions
- Explain memory-mapped files. Efficient large data.
- How to secure serialization? Use secure formats.
- Analytical: Performance in file I/O. Buffering strategies.
- What is isolated storage? Sandboxed file access.
- Scenario: Asynchronous file reading. Use File.ReadAllTextAsync.
Topic 9: .NET Framework and CLR
Core runtime concepts.
Beginner Questions
- What is CLR? Executes managed code.
- Explain JIT compiler. Compiles IL to native.
- What is assembly? Compiled code unit.
- Differentiate .NET Framework and .NET Core. Core: cross-platform.
- What is IL/MSIL? Intermediate Language.
Intermediate Questions
- Explain AppDomain. Isolation boundary.
- What is metadata in assemblies? Type info.
- How to sign assemblies? Strong naming.
- Explain GAC. Global Assembly Cache.
- Scenario: Versioning in assemblies. Handle conflicts.
Expert Questions
- What is Source Generators? Compile-time code gen.
- Explain AOT compilation. Ahead-of-time.
- Analytical: CLR security models. Code access security.
- How to interop with COM? Use ComVisible.
- Scenario: Custom runtime hosting. Embed CLR in apps.
- Bonus: What is ref local variables? Reference to variables.
- Bonus: Explain pattern matching. Switch on types.
- Bonus: What are records? Immutable data classes.
No comments:
Post a Comment
Thanks for your valuable comment...........
Md. Mominul Islam