C#/.Net Flashcards

(181 cards)

1
Q

String vs stringbuilder

A

String is immutable - if you modify it, a new string is created.
SB is mutable, any manipulation done on it, won’t create a new instance each time.
If you want to change a string multiple times, SB is a better option from performance pov BC it won’t require new memory each time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Covariance Vs contravariance

A

Covariance (out)
- allows a method to return a more derived type than specified by the generic parameter.
- supports assignment compatibility from more derived to less derived types (ie derived to base)
- used mostly in return types
Example:
IEnumerable<string> strings = new List<string>();
IEnumerable<object> objects = strings; // Valid because IEnumerable<out> is covariant</out></object></string></string>

Contravariance (in)
- allows a method to accept parameters of less derived types than specified by the generic parameter.
- supports assignment compatibility from less derived types to more derived types (ie Base to Derived)
- used mostly in input parameters
Action<object> actObject = obj => Console.WriteLine(obj);
Action<string> actString = actObject; // Valid because Action<in> is contravariant</in></string></object>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a value type in C#?

A

A value type holds data directly, is stored on the stack, and a copy is made when assigned to another variable. Examples: int, float, bool, struct, enum.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a reference type in C#?

A

A reference type holds a reference to data stored on the heap. When assigned, the reference is copied, so both variables point to the same object. Examples: class, string, array, object, delegate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Where are value types stored in memory?

A

On the stack.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Where are reference types stored in memory?

A

On the heap (the reference itself is on the stack).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Can value types be null?

A

No, unless they are nullable using ?, e.g., int

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Can reference types be null?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What happens when you assign one value type variable to another?

A

A copy of the value is made. The two variables are independent

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What happens when you assign one reference type variable to another?

A

The reference is copied. Both variables point to the same object in memory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the difference between an array and a List in C#?

A

An array has a fixed size and is defined using [], while a List (List<T>) is dynamic and can grow or shrink. Lists offer more built-in methods (like Add, Remove, Contains) and are generally easier to work with, while arrays are slightly more performant and memory-efficient for static data.</T>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a dictionary/map, and when would you use it?

A

A Dictionary (or Map) in C# is a collection of key-value pairs where each key is unique. It allows fast lookups, additions, and deletions by key.
Use it when you need to quickly access data by a specific identifier (like a name, ID, or key).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a singleton?

A

A Singleton is a design pattern that ensures a class has only one instance and provides a global point of access to it. It’s commonly used for things like configuration, logging, or shared resources.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the difference between Dictionary and HashSet in C#?

A

A Dictionary<TKey, TValue> stores key-value pairs, where each key is unique and maps to a value.
A HashSet<T> stores only unique values, with no key—just the values themselves.</T>

Use Dictionary when you need to look up a value by a key.
Use HashSet when you only care about uniqueness and fast existence checks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How does a static field differ from a non-static field?

A

A static field belongs to the class itself and is shared across all instances. A non-static field belongs to a specific instance of the class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How would you call a static method vs an instance method?

A

A static method is called using the class name (e.g., ClassName.Method()), while an instance method is called on an object (e.g., object.Method()).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is boxing and unboxing in C#?

A

Boxing is converting a value type to an object. Unboxing is extracting the value type from the object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is a namespace and what is its purpose?

A

A namespace is a way to organize code and avoid naming conflicts by grouping related classes, interfaces, and types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are the access modifiers in C#, and how do they differ?

A

public: accessible from anywhere.

private: accessible only within the same class.

protected: accessible in the class and its subclasses.

internal: accessible within the same assembly.

protected internal: accessible in the same assembly or derived classes.

private protected: accessible in the containing class or derived classes in the same assembly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the using statement used for, and what interface supports it?

A

The using statement ensures that resources are disposed automatically. It works with types that implement IDisposable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the difference between abstract classes and interfaces in C#?

A

Abstract class can provide both implementation and abstraction.

Interface provides only abstraction (no implementation, until C# 8).
Use an interface for capabilities across unrelated classes; use an abstract class for base functionality in related classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How does async/await work, and what is its purpose?

A

async/await allows for asynchronous programming without blocking the main thread. await pauses execution until the awaited task is complete, while async marks a method to support await.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the yield keyword used for in C#?

A

yield is used to return elements one at a time in an iterator block. It is commonly used with IEnumerable to implement custom iteration.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What LINQ method filters results?

A

Where()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What LINQ method projects or converts data?
Select()
26
What LINQ method sorts results?
OrderBy() and OrderByDescending()
27
How are IEnumerable and IQueryable similar and different?
Both are used for querying collections. IEnumerable executes queries in memory (LINQ to Objects), while IQueryable allows query translation (like to SQL) and supports deferred execution and remote querying.
28
What do the letters MVC stand for, and what are their responsibilities?
Model: Manages data and business logic. View: Handles UI/display. Controller: Handles input, interacts with model, and selects view to render.
29
What are common return types for an MVC action?
ViewResult, JsonResult, RedirectResult, ContentResult, FileResult, ActionResult, and IActionResult.
30
What is dependency injection and why is it important?
Dependency Injection (DI) is a design pattern that provides dependencies from outside a class. It improves modularity, testability, and maintainability.
31
What are the 3 DI scopes and their differences?
Transient: A new instance is created every time it's requested. Scoped: One instance per request (or scope). Singleton: A single shared instance is used throughout the app's lifetime.
32
What is async programming in C#?
Async programming allows code to run without blocking the main thread, improving responsiveness and scalability.
33
What does an async method return in C#?
Typically it returns Task, Task, or void (only for event handlers).
34
Does calling an async method create a new thread?
Not necessarily. Async methods use the existing thread and resume work when awaited operations complete, often using the thread pool if needed.
35
What is the difference between Task.WaitAll() and Task.WhenAll()?
Task.WaitAll() blocks the calling thread until all tasks complete. Task.WhenAll() is non-blocking and returns a Task that completes when all tasks finish.
36
How does .NET Core (now .NET) work under the hood?
It’s a cross-platform, modular, and lightweight framework that uses the CLR for execution and supports dependency injection, configuration, middleware, etc.
37
What are appsettings and user secrets in .NET?
appsettings.json holds configuration data. User secrets allow you to store sensitive info like API keys securely during development.
38
How does middleware work in .NET?
Middleware components are executed in a pipeline to handle requests and responses. Each can modify the request/response and pass control to the next.
39
What is dependency injection in .NET and why is it important?
DI provides class dependencies from outside, promoting loose coupling, testability, and better architecture.
40
Why code to an interface?
It enables abstraction, improves flexibility, supports interface segregation, allows mocking for unit tests, and follows SOLID principles.
41
Why is understanding abstractions and SOLID principles important?
They promote clean, scalable, and maintainable code, making applications easier to test, extend, and refactor.
42
What if you're unsure about algorithms in .NET interviews?
Know that .NET provides efficient built-in algorithms like sorting and searching, which are usually sufficient for business applications.
43
How would you optimize a LINQ MinBy implementation in .NET (prior to .NET 6)?
The original MinBy (before .NET 6) involves sorting the entire list, which is not efficient. To make it faster, you can iterate through the list once, tracking the minimum element as you go, which reduces the time complexity from O(n log n) (sorting) to O(n).
44
What is the common mistake people make when finding the smallest element in a list?
Many candidates only think of sorting the list and picking the first element, which is inefficient. The more efficient solution is to scan the list once while keeping track of the minimum value.
45
How does garbage collection (GC) work in .NET?
The GC automatically reclaims memory by identifying objects that are no longer accessible by any references. It runs in the background and frees memory for reuse.
46
What happens when an object is collected by the GC?
The memory occupied by the object is marked as free, and if the object has a finalizer, it runs before the memory is reclaimed.
47
How does the GC know what can be collected?
The GC tracks object references; if no active references point to an object, it is considered unreachable and eligible for collection.
48
What happens when an object is collected by the GC?
The memory occupied by the object is marked as free, and if the object has a finalizer, it runs before the memory is reclaimed.
49
What is reference counting, and how does it work?
Reference counting tracks how many references point to an object. When the count reaches zero, the object can be safely deallocated. .NET's GC does not use reference counting, but some systems (like COM) do.
50
What kinds of things create garbage in .NET?
Unused objects, temporary variables, boxed value types, closures, and short-lived objects allocated in loops can all create garbage.
51
What is the difference between the stack and the heap in memory?
The stack is used for static memory allocation (value types, method calls), while the heap is for dynamic memory allocation (reference types, objects).
52
How does a variable end up on the stack vs. the heap?
Value types go on the stack unless boxed; reference types and objects created with new go on the heap.
53
Which is faster, the stack or the heap, and why?
The stack is faster because allocation and deallocation are simple (LIFO), and it doesn’t require GC.
54
What are the performance characteristics of common containers?
Containers differ in memory use and access speed. For example, List has O(1) access time, while LinkedList has O(n) for indexing.
55
What is the difference between iterating a List and a List?
List (value types) stores data inline, often improving cache locality and reducing GC pressure. List (reference types) stores references, which may cause cache misses.
56
What is a cache miss?
A cache miss occurs when the CPU has to fetch data from main memory because it is not found in the CPU cache, leading to slower performance.
57
How can you reduce cache misses in .NET?
Use value types with good memory layout, access memory sequentially, and avoid unnecessary indirection and scattered memory access.
58
How do exceptions flow in a using block in C#?
if an exception is thrown inside a using block, the exception is propagated after the Dispose() method is called on the used resource. The resource is always cleaned up, even if an exception occurs.
59
How do exceptions flow in an async method with await?
If an awaited task throws an exception, the exception is captured and re-thrown at the point of the await. The exception is stored in the task and must be handled using try/catch around the await.
60
What happens if an exception occurs before an await in an async method?
The exception is thrown synchronously, just like in a regular method. It does not go through the task's faulted state.
61
Does using work with await and asynchronous code?
Standard using does not await DisposeAsync(). For async cleanup, use await using (C# 8.0+) with types that implement IAsyncDisposable.
62
How does exception handling differ with await using?
DisposeAsync() is awaited after the block, so any exceptions from async cleanup are also awaitable and can be caught in the same try/catch.
63
What is the difference between synchronous and asynchronous code?
Synchronous code runs sequentially and blocks the thread until the operation completes. Asynchronous code allows the thread to continue executing other tasks while waiting for operations to complete.
64
Can async methods be void? When should they be?
Yes, async methods can return void, but only use it for event handlers. Otherwise, use Task or Task to allow proper exception handling and awaiting.
65
What happens if you forget to await an async method?
The method runs in the background, and exceptions may be unobserved or swallowed. It can lead to bugs and unpredictable behavior.
66
What is ConfigureAwait(false) and when should you use it?
It tells the compiler not to resume on the captured context (e.g., UI thread). Use it in library code to improve performance and avoid deadlocks.
67
What is deadlock in async code and how can it happen?
Deadlocks can occur when Task.Wait() or .Result is used on an async method, blocking the thread that is needed to continue execution.
68
Can you mix synchronous and asynchronous code?
Yes, but mixing must be done carefully to avoid deadlocks and maintain responsiveness. Avoid blocking async code with .Result or .Wait().
69
What’s the difference between Task.Run() and async methods?
Task.Run() explicitly runs code on a thread pool thread; async methods may or may not use new threads, depending on awaited operations.
70
What is the difference between concurrency and parallelism?
Concurrency is about dealing with multiple tasks at once (time-slicing), while parallelism is about doing multiple tasks simultaneously (multi-threading).
71
Is async the same as parallel?
No. Async is about non-blocking code execution, often on a single thread. Parallelism involves multiple threads doing work at the same time.
72
When would you use Parallel.For instead of async/await?
Use Parallel.For for CPU-bound tasks to utilize multiple cores. Use async/await for I/O-bound tasks to avoid blocking threads.
73
What is the thread behavior of async vs. parallel code?
async/await typically uses a single thread and resumes work asynchronously. Parallel methods use multiple threads to run code concurrently.
74
What is an event in C#?
An event is a way for a class to provide notifications to subscribers when something of interest occurs. It is based on delegates.
75
What is an event handler?
An event handler is a method that is executed in response to an event being raised. It matches the event's delegate signature.
76
How do you declare an event in C#?
Use the event keyword with a delegate type, e.g., public event EventHandler MyEvent;.
77
How do you raise an event in C#?
Use the null-conditional operator: MyEvent?.Invoke(this, EventArgs.Empty);.
78
What is the standard signature for an event handler?
void HandlerName(object sender, EventArgs e) — sender is the source, and EventArgs carries event data.
79
What is EventArgs?
EventArgs is the base class for passing data with an event. You can create custom classes inheriting from it to pass specific data.
80
What is the difference between a delegate and an event?
A delegate is a type that references a method. An event is a wrapper around a delegate that restricts external invocation (only the declaring class can raise it).
81
Can an event have multiple subscribers?
Yes. Events in C# are multicast, so multiple methods can be attached and will be called in order.
82
How do you unsubscribe from an event?
Use the -= operator: MyEvent -= MyHandler;.
83
What happens if you don’t unsubscribe from an event?
It can cause memory leaks because the event publisher holds a reference to the subscriber, preventing garbage collection.
84
Can events be async in C#?
Events themselves are not async, but you can subscribe an async void handler. However, use with caution due to lack of exception handl
85
What is a memory leak?
A memory leak occurs when memory that is no longer needed is not released because it’s still referenced, preventing garbage collection.
86
Can memory leaks happen in .NET with garbage collection?
Yes. Even with GC, memory leaks can occur if objects are unintentionally held in memory through strong references, static fields, or event handlers.
87
What are common causes of memory leaks in C#?
Not unsubscribing from events Long-lived static references Caching without eviction Improper use of IDisposable Leaking closures in lambdas
88
How can event subscriptions cause memory leaks?
If an object subscribes to an event but never unsubscribes, the publisher retains a reference, keeping the subscriber alive.
89
How can you prevent memory leaks in C#?
Unsubscribe from events Dispose objects with IDisposable Use weak references when needed Avoid unnecessary static references
90
What tool can be used to detect memory leaks in .NET?
Tools like dotMemory, PerfView, Visual Studio Diagnostic Tools, or CLR Profiler can help identify memory leaks.
91
What is a strong reference?
A reference that prevents an object from being collected by the GC as long as the reference exists.
92
What is a weak reference?
A reference that does not prevent garbage collection. It allows you to reference an object without keeping it alive.
93
How does IDisposable help manage memory?
It allows manual release of unmanaged resources (like file handles, streams), which are not cleaned up by the GC.
94
What happens if you forget to call Dispose() or use a using block?
Unmanaged resources may not be released, leading to memory/resource leaks and potential performance issues.
95
How can you send a file over HTTP in a Web API?
Return a FileContentResult, FileStreamResult, or use File(byte[], contentType, filename) in an action.
96
How do you read a file into a byte array in C#?
Use File.ReadAllBytes(path) to load the entire file as a byte[].
97
How do you write a byte array to a file in C#?
Use File.WriteAllBytes(path, byteArray).
98
How do you read binary data from a stream in C#?
Use BinaryReader to read binary types (e.g., int, string, etc.) from a Stream.
99
How do you write binary data to a stream in C#?
Use BinaryWriter to write binary types to a Stream.
100
How do you convert a string to bytes in C#?
Use Encoding.UTF8.GetBytes(string) (or any other Encoding).
101
How do you convert bytes to a string in C#?
Use Encoding.UTF8.GetString(byte[]).
102
How can you encode binary data for safe transfer in JSON or XML?
Use Base64 encoding: Convert.ToBase64String(byte[]).
103
When should you implement a finalizer?
Only when your class directly handles unmanaged resources (e.g., file handles, OS handles) that must be released explicitly.
104
What is unmanaged memory?
Memory that is not controlled by the .NET runtime (GC), such as memory allocated using Marshal.AllocHGlobal or through interop with native code.
105
How do you free unmanaged memory in C#?
Use APIs like Marshal.FreeHGlobal and implement IDisposable to ensure cleanup happens manually or through using blocks.
106
What is GC.Collect() and when should you use it?
GC.Collect() forces garbage collection. It's rarely needed in production and should only be used for debugging or memory-sensitive scenarios with full understanding of its impact.
107
How do you read binary data from a stream in C#?
Use BinaryReader to read binary types (e.g., int, string, etc.) from a Stream.
108
How do you write binary data to a stream in C#?
Use BinaryWriter to write binary types to a Stream.
109
How do you convert a string to bytes in C#?
Use Encoding.UTF8.GetBytes(string) (or any other Encoding).
110
What are GC generations in .NET?
Gen 0: Short-lived objects Gen 1: Objects that survived Gen 0 Gen 2: Long-lived objects GC collects lower generations more frequently to improve efficiency.
111
How do you convert bytes to a string in C#?
Use Encoding.UTF8.GetString(byte[]).
112
How can you encode binary data for safe transfer in JSON or XML?
Use Base64 encoding: Convert.ToBase64String(byte[]).
113
How can you decode Base64 data back to binary?
Use Convert.FromBase64String(string) to get the original byte[].
114
How do you send a file in an HTTP request using HttpClient?
Use MultipartFormDataContent with ByteArrayContent or StreamContent, and attach the file.
115
How can you stream large files without loading them entirely in memory?
Use FileStream with StreamContent or return FileStreamResult in ASP.NET to stream files efficiently.
116
What is the benefit of streaming files vs sending byte arrays?
Streaming uses less memory and supports large files efficiently, whereas byte arrays require loading the full file into memory.
117
What is binary data, byte, byte array, stream?
Binary data refers to data in its raw form—sequences of 0s and 1s—not human-readable, used for files, media, protocols, etc. byte is a unit of digital information consisting of 8 bits. It can represent values from 0 to 255. A byte[] is an array of bytes in memory, commonly used to store or manipulate binary data. A stream is an abstraction for reading/writing data sequentially (e.g., from files, network, memory) without loading everything at once. How is a stream different from a byte array? A: A stream allows sequential access and can handle large data efficiently. A byte array is a complete, in-memory representation of all data.
118
How is a stream different from a byte array?
A: A stream allows sequential access and can handle large data efficiently. A byte array is a complete, in-memory representation of all data.
119
What is MemoryStream used for?
MemoryStream is a stream backed by a byte array, useful for in-memory I/O operations.
120
What is FileStream used for?
FileStream provides stream-based access to files, allowing efficient reading/writing of file data.
121
What is StreamReader / StreamWriter?
These are wrappers over streams for reading/writing text data using encodings.
122
What is BinaryReader / BinaryWriter?
These classes read and write primitive types (e.g., int, float, string) to and from a stream in binary format.
123
When would you use a stream instead of a byte[]?
Use streams for large files or network data to avoid high memory usage; use byte[] for small, fully-loaded data chunks.
124
How can you optimize GC performance?
Minimize object allocations Reuse objects Avoid large object allocations when possible Use Span, ArrayPool for buffer reuse Reduce frequency of GC triggers
125
What is the Large Object Heap (LOH)?
A special heap for large objects (>85,000 bytes). It is only collected during Gen 2 collections and can fragment memory.
126
How can you reduce LOH fragmentation?
Avoid allocating many large arrays/strings Reuse large buffers Use ArrayPool Use GCSettings.LargeObjectHeapCompactionMode (in .NET Core+)
127
How can you prevent finalizer delays in cleanup?
Implement IDisposable and suppress the finalizer using GC.SuppressFinalize(this) after releasing resources in Dispose().
128
How do you read a file into a byte array in C#?
Use File.ReadAllBytes(path) to load the entire file as a byte[].
129
How do you write a byte array to a file in C#?
Use File.WriteAllBytes(path, byteArray).
130
What is IEnumerable?
IEnumerable is an interface for in-memory collection iteration. It supports LINQ-to-Objects and executes queries in memory.
131
What is IQueryable?
IQueryable allows querying data from external sources (like a database) using LINQ. Queries are translated to SQL or other providers and executed remotely.
132
What is the main difference between IEnumerable and IQueryable?
IEnumerable executes queries in memory, while IQueryable builds an expression tree and defers execution to the data source.
133
Does IEnumerable or IQueryable support deferred execution?
Both support deferred execution, but IQueryable defers execution to the data source, potentially optimizing the query.
134
When would you use IEnumerable and when would you use IQueryable?
Use IEnumerable when working with in-memory collections or after data is already loaded. Use IQueryable for querying databases or remote sources where you want the query to be translated and executed server-side.
135
Which is more efficient for database queries: IEnumerable or IQueryable?
IQueryable is more efficient because it translates the query into SQL and fetches only the required data.
136
What happens if you use ToList() on an IQueryable?
It forces execution of the query and materializes the result into a list, turning it into an in-memory IEnumerable.
137
Can you switch from IQueryable to IEnumerable?
Yes. Calling methods like ToList(), ToArray(), or AsEnumerable() executes the query and switches to IEnumerable.
138
Can you use custom methods with IQueryable?
No. IQueryable needs expressions that can be translated (e.g., to SQL). Custom methods will throw runtime errors or break translation.
139
What is the ASP.NET Core request pipeline?
It's a sequence of middleware components that process HTTP requests and responses.
140
What is middleware in ASP.NET Core?
Middleware is a piece of code that can handle requests, responses, or both, and optionally pass control to the next component in the pipeline.
141
How does a request flow through the pipeline?
The request enters the first middleware, which can handle it or pass it down to the next. Eventually, a response is returned and flows back up through the middleware.
142
What are examples of built-in middleware?
UseRouting() UseAuthentication() UseAuthorization() UseEndpoints() UseStaticFiles() UseExceptionHandler()
143
What is UseRouting() and where should it be in the pipeline?
UseRouting() matches the incoming request to route definitions. It should come before UseAuthorization() and UseEndpoints().
144
What is UseEndpoints()?
UseEndpoints() is the terminal middleware that executes the matched endpoint, like a controller action or Razor Page.
145
Why is the order of middleware important?
Middleware order affects how requests are handled. Some middleware (e.g., routing, authentication) must appear before others to function properly.
146
How do you add custom middleware?
Create a class with an Invoke or InvokeAsync method, then register it in Startup.Configure using app.UseMiddleware().
147
What happens if middleware doesn't call next()?
The request stops there, and downstream middleware and the response won’t be executed or returned.
148
What is terminal middleware?
Middleware that doesn’t call next() and ends the pipeline (e.g., app.Run() or UseEndpoints()).
149
Difference between == Vs .Equals()
"==" compares if obj ref are the same ".Equals()" method compares the contents
150
How does garbage collector work in .net
The GC in .net automatically manages memory by identifying and reclaiming memory occupied by objects that are no longer in use. The GC operates in generations (0,1,2) to optimise performance, with objects being promoted to higher generations if they survive collections. The GC runs periodically, compacts memory and updates references
151
How do you enable parallelism in a LINQ query using PLINQ?
Parallelism in a LINQ query is enabled by calling the As parallel method on the data source. var result = dataSource.AsParallel().Where(x => x.SomeCondition).To list();
152
What is PLINQ and how does it differ from LINQ
PLINQ (Parallel LINQ) is an extension of LINQ that enables parallel processing of queries. It leverages multiple processors for improved performance by executing LINQ queries in parallel. PLINQ provides methods like As parallel to enable parallelism and can significantly speed up operations on large data sets.
153
What are common data structures in c#
Arrays - fixed size, contiguous memory allocations for storing elements of the same type. Lists - dynamic arrays that provide flexible size and additional methods for manipulating collections Dictionaries - key value pairs for efficient lookups Stacks & queues - LIFO and FIFO structures Trees and graphs - hierarchical and networked data structures for complex relationships
153
What are some common performance optimization techniques in C#
1. Avoid unnecessary allocations - minimise allocations to reduce garbage collection overhead. 2. Using Value types efficiently - prefer struts for small immutable data to avoid heap allocations. 3. StringBuilder for string manipulation - use SB for frequent string concatenations to avoid creating multiple immutable string instances 4. Efficient LINQ usage - avoid unnecessary enumerations and prefer methods like ToArray or ToList to materialise results when needed
154
How to measure performance of your c# app
Performance cancelled be measured using profiling tools like VS profiler, dotTrace, and benchmarkDotNet. These tools help efficiently identify bottlenecks, measure execution time, memory usage, and analyse CPU and memory allocations
155
Explain the time complexity of common operations on a dictionary in C#
The average time for insert, delete and lookup operations in a dictionary is O(1) due to its hash-based implementation. However in the worst case (eg hash collisions) the time complexity can degrade to O(n)
156
Explain the key differences between LINQ to Objects, LINQ to SQL and LINQ to XML
LINQ to objects - queries in memory collections like arrays and lists. LINQ to SQL - queries relational databases & translates LINQ queries into SQL queries executed by the database. LINQ to XML - queries and manipulates XML using LINQ syntax
157
What's LINQ and how is it used in c#
It's a feature that allows querying of collections using a syntax integrated into the language. It supports querying various data sources, including arrays, collections, databases and XML. LINQ provides a consistent query experience across different types of data
158
What are IoC containers & how do they work
Inversion of control (IoC) containers are frameworks that manage the creation, configuration and lifetimes of dependencies. They automatically inject the required dependencies into classes, supporting various lifetimes (eg singleton, scoped, transient) and enabling developers to focus on business logic rather than dependency management
159
What is dependency injection and why is it used?
Dependency injection is a design pattern that allows a class to receive it's dependencies from an external source rather than creating them internally. DI promotes loose coupling, easier testing and better maintainability by managing dependencies through configuration.
160
What are pitfalls of async/await in C#
Some pitfalls include - deadlocks - occur when the context is captured unnecessarily, esp in UI or .net apps - exception handling - async exceptions need to be properly handled using try/catch blocks within async methods - resource management - incorrect handling of resources can lead to memory leaks in if tasks are not awaited properly or cancelled appropriately
161
Wahat is the Task Parallel Library (TPL) in C#
TPL is a set of APIs in .net for parallel programming and task based asynchronous programming. It simplified the process of writing concurrent and parallel code by providing classes like Task and Parallel, which abstract the complexity of threading & provide a higher level of abstraction for managing parallelism.
162
How does the Task class differ from Thread class in C#
The task class is a higher level abstraction that represents an asynchronous operation, providing better control & management of asynchronous code. The thread class represents a lower level, OS managed thread. Tasks are more efficient and easier to work with company we to threads.
163
What is the purpose of the ConfigureAwait(false) method in async programming?
ConfigureAwait(false) is used to avoid capturing the current context when awaiting a task, which can improve performance and prevent deadlocks I'm certain scenarios, such as the UI app where the context is the UI thread. It should be used when the context is not needed after the await operation.
164
What's the purpose of the 'this' keyword in C#
It refers to the current instance of the class within an instance method or constructor. It's used to access members (methods, properties, fields) of the current object esp when there's a naming conflict between method parameters and class fields
165
What's encapsulation and how to achieve this in C#
Encapsulation is the practice of bundling data (fields) and methods that operate on that data into a single unit or class, while restricting access to the inner workings of that class. It's achieved by using access modifiers like private, protected, internal and public to control the visibility of class members
166
167
What's polymorphism and how's it implemented in C#
Polymorphism allows objects of different classes to be treated as objects of a common superclass, typically though inheritance. It's implemented through method overriding (runtime polymorphism) using the virtual and override keywords and method overloading (compiled time polymorphism)
168
How does async/await work, and what's its purpose
The async keyword is used to declare a method as async and the await network is used to suspend the execution of the method until the awaited task completes. This allows for non-blocking I/O operations, improving the responsiveness of apps
169
What's async programming and whys it important
Async programming allows for the execution of tasks without blocking the main thread, ending apps to remain responsive, especially in I/O bound operations like file access, network requests or dB queries. It improves the scalability and performance of apps by allowing multiple tasks to run concurrently
170
Difference between Finalizer and IDisposable
A Finalizer (~ClassNamr) is used to release unmanaged resources before an object is reclaimed by the garbage collector. IDisposable provides a Dispose method for explicit resource cleanup. iDisposable is preferred for deterministic disposal, while finalizers are a safety net for unmanaged resources
171
Difference between a class and a struct in C#
Class - a reference type that supports inheritance and is allocated on the heap. Classes can have constructors, destructors and finalizers. Struct - a value type that doesn't support inheritance (except for implementing interfaces) and is allocated on the stack. Structs are typically used for lightweight objects that don't require the overhead of heap allocation
172
Difference between reference and value type
Value types store their data directly, while reference types store a reference to the data's memory address. Value types are typically stored on the stack, whereas reference types are stored on the heap. Examples of value types include int, float, and strict while examples of reference types include class, array and string.
173
What's a singleton
It's a design pattern that ensures a class has only one instance and provides a global point of access to it. This can be implemented by making the constructor private, creating a static field to hold the instance and providing a static method that returns the instance
174
Array Vs list?
Array has a fixed size & hold elements of a single type. A list, part of the system.collections.generic namespace, is dynamic and can grow and shrink in size. Lists also provide more methods to manipulation the collection
175
What's a dictionary/map and when to use?
A collection of key/value pairs where each key is unique. It's used when you need to quickly lookup values based onto their keys. In c# the Dictionary class is commonly used
176
How do dictionary/maps differ from hashset?
A hashset is a collection of unique values and doesn't allow duplicate elements. It's primarily used for fast lookups and ensuring a collection contains no duplicates. Unlike a dictionary it only stores values, not keys
177
How does a static field differ from a non static field?
A static field belongs to the class itself and is shared amongst all instances of the class, while a non static field belongs to an instance of the class. Static fields are accessed using the class name, whereas non static fields are accessed through instances
178
How to call a static method Vs instance method?
A static method is called using the class name (eg ClassName.StaticMethod()) while an instance method is called using an object of the class
179
What's boxing and unboxing?
Boxing is the process of converting a value type to an object type, essentially wrapping the value in an object reference. Unboxing is the process of extraction the value type from the object. Boxing incurs a performance penality due to additional memory allocation and GC
180
What's a namespace and it's purpose?
A namespace is a container for classes and other types, used to organise code and avoid name collisions. It allows for the logical grouping of related types and helps manage large codebases