أسئلة القسم
تدرب على أسئلة المقابلات في هذا القسم. اكتب إجابتك، قم بتقييمها، أو اضغط على "عرض الإجابة" بعد التفكير.
What is .NET? Explain its architecture (CLR, CTS, etc.). سهل
.NET is a free, cross-platform, open-source developer platform for building applications (web, desktop, mobile, cloud, gaming, IoT).
Main components of .NET architecture:
- CLR (Common Language Runtime): Execution engine. Handles memory management, garbage collection, exception handling, JIT compilation.
- CTS (Common Type System): Defines how types are declared and used across all .NET languages (C#, VB, F#).
- CLS (Common Language Specification): A subset of CTS rules to ensure cross-language interoperability.
- BCL/FCL (Base Class Library / Framework Class Library): Provides reusable classes (collections, IO, networking, etc.)
What is different between .Net framework and .Net framework Core? سهل
Feature | .NET Framework | .NET Core / .NET (modern) |
---|---|---|
Platform | Windows only | Cross-platform (Win, Linux, macOS) |
Open Source | Partially | Fully open source (on GitHub) |
Performance | Slower (monolithic) | High performance, modular |
Deployment | Requires installation on system | Can be self-contained (xcopy deploy) |
Future | Legacy (no active dev) | Actively developed → .NET 8/9 |
What is Json? سهل
JSON (JavaScript Object Notation) is a lightweight, text-based format for data exchange.
- Human-readable, language-independent, used in APIs.
What is the difference between continue and break? سهل
- break → Exits the loop completely.
- continue → Skips current iteration, moves to next.
What is the difference between == and .Equals()? سهل
- == → Operator. By default, checks reference equality (for objects), value equality (for primitives/structs).
- .Equals() → Virtual method, can be overridden for custom equality.
What is the difference between const and readonly? سهل
const
- Compile-time constant
- Must be initialized inline
- Implicitly static
readonly
- Runtime constant
- Can be assigned in constructor
- Different value per instance possible
What is the difference between var, dynamic, and object? سهل
Keyword | Resolves at | Type safety | Use case |
---|---|---|---|
var | Compile time | Strongly typed | Inferred local variables |
dynamic | Runtime | No compile-time checking | Interop (COM, JSON, reflection) |
object | Compile time (base type) | Requires casting | General-purpose type |
What are default values of types in C#? سهل
- Value types: 0 for numeric, false for bool, '\0' for char.
- Reference types: null.
What is the difference between for and foreach? سهل
for:
- Index-based
- Flexible (can manipulate index)
foreach:
- Cleaner, read-only iteration
- Can’t modify underlying collection size
What is different between list and array? سهل
Feature | Array | List |
---|---|---|
Size | Fixed | Dynamic |
Performance | Faster (no overhead) | Slightly slower |
Type | Can be multi-dimensional | Generic, one-dimensional |
Methods | Limited | Rich methods (Add, Remove, etc.) |
Explain the difference between String and StringBuilder? سهل
String: Immutable → Every change creates a new object. StringBuilder: Mutable → Efficient for many modifications.
What are value and reference types? What is the difference between them? سهل
- Value types: Stored in stack, hold actual data. (e.g., int, struct).
- Reference types: Stored in heap, variable holds reference (e.g., class, string).
What is the difference between Array, ArrayList, and List<T>? متوسط
Feature | Array | ArrayList (non-generic) | List |
---|---|---|---|
Type safety | Strongly typed | Stores object → boxing/unboxing |
Strongly typed (generic) |
Size | Fixed | Dynamic resizing | Dynamic resizing |
Performance | Fastest (no overhead) | Slower due to boxing/unboxing | Better than ArrayList |
Usage | Simple, fixed size | Legacy, avoid in new code | Preferred in modern .NET |
What is the difference between List<T> and LinkedList<T>? متوسط
Feature | List |
LinkedList |
---|---|---|
Memory layout | Contiguous array | Nodes linked with pointers |
Access time | O(1) by index | O(n) by index |
Insert/Delete | O(n) in middle, O(1) at end | O(1) if node reference known |
Use case | Frequent reads, index access | Frequent inserts/deletes |
What is the difference between Stack<T> and Queue<T>? سهل
Stack
- Methods: Push(), Pop(), Peek().
Queue
- Methods: Enqueue(), Dequeue(), Peek().
What is the difference between Dictionary<TKey,TValue> and Hashtable? متوسط
Feature | Dictionary<TKey,TValue> | Hashtable |
---|---|---|
Type safety | Generic → strongly typed | Stores as object (boxing/unboxing) |
Performance | Faster (no boxing) | Slower for value types |
Thread safety | Not thread-safe by default | Some synchronization support |
Usage | Preferred in .NET Core | Legacy, avoid in new code |
When would you use SortedDictionary vs SortedList? متوسط
SortedDictionary<TKey, TValue>
- Backed by a binary search tree (red-black tree).
- Better for frequent inserts/deletes.
SortedList<TKey, TValue>
- Backed by arrays.
- Better for smaller collections and frequent lookups.
What is the difference between IEnumerable, ICollection, IList, and IDictionary? صعب
- IEnumerable: Forward-only iteration (foreach).
- ICollection: Extends IEnumerable, adds Count, Add, Remove.
- IList: Extends ICollection, supports index-based access.
- IDictionary: Key-value pairs, extends ICollection.
What is the difference between IEnumerable and IEnumerator? متوسط
- IEnumerable: Represents a collection that can be iterated. Provides GetEnumerator().
- IEnumerator: Represents the enumerator that actually iterates. Provides MoveNext(), Current, Reset().
What is the difference between IEnumerable and IQueryable? صعب
Feature | IEnumerable | IQueryable |
---|---|---|
Execution | In-memory (LINQ to Objects) | Deferred, query provider (e.g., EF Core → SQL) |
Filtering | Done in memory | Translated to remote query (DB, API) |
Performance | Can be slower for large data | Efficient for remote data sources |
How does HashSet<T> handle duplicates? سهل
HashSet
- Internally uses hashing; if hash code + equality match an existing item, new one is ignored.
How does Dictionary<TKey, TValue> handle key collisions? متوسط
- Uses a hash code of the key → bucket index.
- If multiple keys map to same bucket:
- Uses equality comparer (Equals) to differentiate.
- Stores colliding items in linked entries.
- In .NET Core, collisions are resolved with chaining.
What is a delegate? متوسط
A delegate is a type-safe reference to a method.
- Supports callback mechanisms, event handling, LINQ expressions.
What is Serialization? متوسط
Serialization: Converting an object into a format (JSON, XML, binary) to store or transfer.
- Example: Save object to a file or send over network.
What is DeSerialization? متوسط
Converting serialized data back into an object.
What's the difference between XmlDocument and XmlReader? متوسط
Feature | XmlDocument | XmlReader |
---|---|---|
Model | DOM (loads entire XML tree in memory) | Forward-only reader |
Memory | High (whole doc) | Low (reads node by node) |
Usage | Easy to navigate, modify | Efficient for large XML |
Performance | Slower for big XML | Faster, streaming-based |
What are ref, out, and in parameters? متوسط
- ref → Passes variable by reference (must be initialized before).
- out → Passes variable by reference, but must be assigned inside method.
- in → Passes by reference but as readonly (cannot modify inside method).
What is the difference between value parameter and ref parameter? متوسط
Value parameter (default):
- A copy of the argument is passed.
- Changes inside the method don’t affect the original variable.
Ref parameter:
- Passes reference to the original variable.
- Must be initialized before passing.
- Changes inside the method affect the caller.
What is the difference between shallow copy and deep copy in C#? صعب
Shallow Copy:
- Copies object’s fields as is.
- Reference fields still point to the same objects.
- Example: MemberwiseClone().
Deep Copy:
- Copies the object and all referenced objects recursively.
- Requires custom implementation or serialization.
What is the difference between is and as operators? متوسط
- is: Checks type compatibility, returns true/false.
- as: Attempts safe cast, returns null if it fails (no exception).
What is boxing and unboxing in C#? متوسط
- Boxing: Converting a value type → object (heap allocation).
- Unboxing: Extracting value type from object.
What are iterators and the yield keyword? متوسط
- Iterator: A method that returns elements one at a time (lazy evaluation).
- yield return: Produces a value and remembers state for next iteration.
- yield break: Ends iteration.
What is a Tuple and how is it different from an anonymous type? متوسط
- Tuple: Lightweight data structure, supports multiple values. Mutable.
- Example: var t = Tuple.Create(1, "Book");
- Anonymous type: Compiler-generated class, read-only properties, scoped to method.
- Example: var obj = new ;
- Key difference: Tuples are reusable return types, anonymous types are method-scoped.
What are records in C# 9+ ? متوسط
Records are reference types introduced in C# 9, optimized for immutable, value-based equality.
What is the difference between records and classes? متوسط
Feature | Class | Record |
---|---|---|
Equality | Reference equality by default | Value equality (compares properties) |
Immutability | Mutable by default | Init-only setters (encourage immut.) |
Use case | Represent entities | Represent data models (DTOs, configs) |
How does the ConcurrentDictionary differ from Dictionary? صعب
Dictionary<TKey,TValue>:
- Not thread-safe for concurrent reads/writes.
- Needs external locking (lock) for multi-threading.
ConcurrentDictionary<TKey,TValue>:
- Designed for thread-safe concurrent access.
- Uses fine-grained locking and lock-free operations internally.
- Provides atomic methods like TryAdd, GetOrAdd, AddOrUpdate.
How does the Span<T> type improve performance in C#? صعب
Span
Benefits:
- Avoids allocations → no new arrays when slicing.
- Improves performance for parsing, processing large data.
- Safe alternative to pointers (bounds-checked).
Limitation: Cannot be stored on heap (because it references stack memory).
Explain covariance and contravariance in generics. صعب
- Covariance (out): lets you use a more derived type than specified. Works with return values.
- Contravariance (in): lets you use a more generic (base) type than specified. Works with parameters.
What is JIT compilation? متوسط
JIT (Just-In-Time) compiles IL (Intermediate Language) to machine code at runtime.
Types:
- Pre-JIT (NGen/AOT): whole assembly ahead of time.
- Econo-JIT: compiles only needed methods, discards unused.
- Normal JIT: compiles as methods are called.
What is the app domain? متوسط
AppDomain: an isolation unit for .NET apps within a process.
- Used to load/unload assemblies without restarting the process.
- In .NET Core/.NET 5+, AppDomains are not supported → replaced with AssemblyLoadContext.
What are nullable types? متوسط
- Value types (int, bool) cannot be null by default.
- Nullable types (int?): wrap them in Nullable
. - Provides HasValue and Value.
What is the size of stack in .NET? صعب
By default:
- 1 MB for main thread.
- 256 KB – 1 MB for worker threads (depends on OS and settings).
- Can be configured using Thread constructor or PE header.
Which objects go on Large Object Heap? صعب
- Objects ≥ 85 KB (mainly large arrays, strings, buffers).
- Stored separately for performance (avoid frequent GC compaction).
In .NET, what exactly is the High Frequency Heap? متوسط
- A GC heap segment optimized for small, frequently allocated objects.
- Introduced with Server GC in .NET 5+.
- Reduces contention by giving each thread its own heap segment.
How does the garbage collector work in .NET? متوسط
- Generational GC: objects are grouped into Gen 0, Gen 1, Gen 2.
- Process:
- Allocations go to Gen 0.
- Short-lived → collected quickly.
- Surviving objects promoted to higher generations.
- Uses mark-and-sweep with compaction.
What are the limitations of garbage collection? صعب
- Non-deterministic (can’t control exactly when GC runs).
- Finalizers delay cleanup.
- Expensive for large heaps (pauses).
- Not aware of unmanaged resources → need IDisposable.
What is the difference between managed and unmanaged environments? (GC pros and cons, JIT pros and cons) صعب
Managed (.NET runtime):
- Pros: GC, memory safety, type safety, security.
- Cons: Overhead (GC pauses, JIT cost).
Unmanaged (C/C++):
- Pros: Full control, high performance.
- Cons: Risk of leaks, buffer overflows, manual memory management.
What is the difference between synchronous and asynchronous methods? متوسط
- Synchronous: blocks until operation completes.
- Asynchronous: frees the thread, continues when operation completes (non-blocking).
What are async/await and how do they improve performance? متوسط
- async/await: syntactic sugar for working with Task.
- Improves responsiveness (UI not blocked, server scales better).
- Doesn’t create new threads (uses I/O completion).
If an async method runs, does it create a new thread? صعب
- No, async methods don’t create new threads by default.
- I/O-bound async uses I/O completion ports.
- CPU-bound async needs Task.Run() (creates a thread).
What is the difference between Task, Thread, and ValueTask? صعب
- Thread: OS thread, heavy, long-lived.
- Task: abstraction for async work, can use thread pool or I/O.
- ValueTask: lightweight struct for performance when result is often available synchronously.
How do you prevent two threads from accessing the same method? متوسط
Use synchronization primitives:
- lock (monitor).
- Mutex, SemaphoreSlim, ReaderWriterLockSlim.
What are thread-safe collections in .NET? صعب
Collections in System.Collections.Concurrent:
- ConcurrentDictionary, ConcurrentBag, BlockingCollection, ConcurrentQueue, ConcurrentStack.
- Provide lock-free or fine-grained locking.
When would you use the lock keyword? متوسط
- When multiple threads access shared state.
- Ensures only one thread executes a block at a time.