Answer:
C# is a modern, object-oriented and type-safe programming language
developed by Microsoft. It is commonly used with the .NET platform
for building desktop, web, API, cloud and other applications.
Interview Tip: Mention that C# is
object-oriented, strongly typed and commonly used with .NET.
Answer:
Important features include object-oriented programming, strong type
checking, automatic memory management through garbage collection,
exception handling, generics, delegates, LINQ and asynchronous
programming.
Interview Tip: Give 3–5 features and
briefly explain one rather than only listing names.
Answer:
C# is a programming language, while .NET is a development platform
and runtime ecosystem that provides libraries, runtime services and
tools for executing applications written in C# and other languages.
Answer:
CLR stands for Common Language Runtime. It provides runtime services
such as memory management, garbage collection, exception handling
and execution support for managed .NET applications.
Answer:
Managed code is code executed under the control of the .NET runtime.
The runtime manages services such as memory allocation, garbage
collection and exception handling.
Answer:
Value types directly contain their data, while reference types
contain a reference to an object. Examples of value types include
int, bool and struct; class, array and string are reference types.
Answer:
Boxing converts a value type to object or another compatible
reference type. Unboxing extracts the value type from the boxed
object and requires a compatible type.
int number = 10;
object obj = number; // Boxing
int value = (int)obj; // Unboxing
Answer: var is resolved at compile time and still has a specific
type. dynamic defers member/type checking to runtime.
object is the base type of the .NET type system and may
require casting to use a specific value.
Answer:
A namespace logically groups related types and helps avoid naming
conflicts between classes, interfaces and other types.
Answer:
A class is a blueprint that defines data and behavior through fields,
properties, methods, constructors and other members. Objects are
instances of classes.
Answer:
An object is an instance of a class. It has state represented by
data and behavior represented by methods.
Answer:
A constructor is a special member used to initialize an object when
it is created. It has the same name as the class and does not have
a return type.
Answer:
Yes. Constructor overloading allows a class to have multiple
constructors with different parameter lists.
Answer:
A const value must be assigned at declaration and is
constant at compile time. A readonly field can be
assigned at declaration or in a constructor and is then not normally
assignable afterward.
Answer:
A static member belongs to the type itself rather than to an
individual object. It can be accessed using the class name.
Answer:
Access modifiers control the visibility of types and members.
Common modifiers include public, private, protected and internal.
Answer:
Method overloading means defining multiple methods with the same
name but different parameter lists. It is compile-time polymorphism.
Answer:
Method overriding allows a derived class to provide a new
implementation for an inherited virtual or abstract member.
Answer:
An interface defines a contract that implementing types agree to
follow. It is commonly used to achieve abstraction and loose
coupling.
Answer:
An abstract class is a class intended to be used as a base class.
It can contain implemented members as well as abstract members that
derived classes must implement.
Answer:
An abstract class can provide shared implementation and state,
while an interface primarily defines a contract. A class can
implement multiple interfaces, while class inheritance has a single
direct base class.
Answer:
A sealed class cannot be inherited. It is useful when a type's
implementation should not be extended through inheritance.
Answer:
A struct is a value type that can contain fields, properties,
methods and constructors. It is commonly useful for small values
where value semantics are appropriate.
Answer:
An enum defines a set of named integral constants, making code
easier to read when a value can belong to a fixed set of choices.
Answer:
A nullable value type allows a value type to also represent null.
For example, int? can contain an integer or null.
Answer:
A string object cannot be modified after it is created. Operations
that appear to change a string create another string object.
Answer:
String is immutable, so repeated modifications can create multiple
objects. StringBuilder is mutable and is generally more suitable
when many string modifications are required.
Answer:
Garbage collection automatically identifies objects that are no
longer reachable and reclaims their managed memory.
Interview Tip: Do not describe GC
as immediately freeing every object after it goes out of scope.
Answer:
IDisposable provides a standard pattern for explicitly releasing
resources such as file handles, database connections or other
unmanaged resources held by an object.
Answer:
The using statement is commonly used with IDisposable resources so
that Dispose is called automatically when execution leaves the
scope.
using (var connection = CreateConnection())
{
connection.Open();
}
Variables & Data Types
Answer: Type inference allows the compiler to determine a local variable's compile-time type from its initializer, commonly when using var.
Answer: An implicit conversion happens automatically when a conversion is safe and no data loss is expected, such as converting an int to a long.
Answer: An explicit conversion requires a cast because the conversion may lose information or is not guaranteed to be safe.
Answer: Casting tells the compiler to treat a value as another compatible type, for example double d = 10.5; int n = (int)d;.
Answer: It converts a compatible value to a 32-bit integer and can handle several input types.
Answer: Parse throws when conversion fails, while TryParse returns false and is safer when invalid input is expected.
Answer: An array stores a fixed-size sequence of elements of the same type.
Answer: A jagged array is an array whose elements are themselves arrays, so inner arrays can have different lengths.
Answer: It is an array with more than one dimension, such as a rectangular matrix.
Answer: A tuple groups multiple values into one lightweight value, useful for returning or carrying related values.
Answer: Nullable reference type annotations help the compiler identify possible null references and warn about unsafe usage.
Answer: The ?? operator returns its left operand when it is not null; otherwise it returns the right operand.
Answer: The ?. operator safely accesses a member only when the preceding expression is not null.
Answer: A default value is the value produced for a type when no explicit value is supplied, such as 0 for numeric value types.
Answer: Two types are compatible when a value of one type can be assigned, converted or cast to the other according to C# rules.
Answer: Reference equality checks whether two references point to the same object, commonly with ReferenceEquals.
Answer: Value equality checks whether two values represent the same logical value, usually through an equality implementation.
Answer: A using alias gives another name to a namespace or type and can resolve naming conflicts.
Answer: A global using makes a namespace or type available across files in the project without repeating the using directive.
Answer: Type pattern matching tests an object's runtime type and can simultaneously introduce a variable of that type.
Answer: The is operator tests whether an expression is compatible with a specified type or pattern.
Answer: The as operator attempts a reference, nullable or boxing conversion and returns null instead of throwing when it fails.
Answer: Integral types represent whole numbers, including byte, short, int, long and their unsigned counterparts.
Answer: Floating-point types such as float and double represent numbers with fractional parts using floating-point representation.
Answer: decimal provides high decimal precision and is commonly used for financial values; double is generally used for scientific and general floating-point calculations.
Answer: The char type represents a single UTF-16 code unit.
Answer: bool represents true or false.
Answer: It is the type known to the compiler for an expression or variable and used for static type checking.
Answer: It is the actual type of an object during execution, which can differ from the compile-time type of a reference.
Answer: Strong typing catches many incompatible operations at compile time and makes APIs easier to reason about.
Control Statements
Answer: It executes a block when a Boolean condition evaluates to true.
Answer: It chooses between two blocks depending on whether a condition is true or false.
Answer: It selects a branch based on a value or pattern and is useful when several alternatives exist.
Answer: A switch expression returns a value based on matching patterns or cases.
Answer: A for loop repeats a block while controlling initialization, condition and iteration in one statement.
Answer: A while loop repeatedly executes its body while its condition remains true.
Answer: A do-while loop executes its body at least once and checks the condition afterward.
Answer: foreach iterates through elements of a sequence without manually managing an index.
Answer: break exits the loop or switch; continue skips the remaining loop body and proceeds to the next iteration.
Answer: return exits the current method and optionally supplies a value to its caller.
Answer: A nested loop is a loop placed inside another loop and is useful for multidimensional or repeated combinations.
Answer: The ternary operator condition ? value1 : value2 chooses one of two expressions.
Answer: Logical operators such as && and || can stop evaluating once the result is known.
Answer: && is conditional logical AND with short-circuiting; & can perform a non-short-circuit Boolean AND and is also a bitwise operator.
Answer: || short-circuits logical OR; | can perform non-short-circuit Boolean OR and bitwise OR.
Answer: In C#, ordinary switch cases do not freely fall through; an explicit control transfer such as goto case is required for certain cases.
Answer: Yes, modern C# switch constructs support type, relational, property and other patterns.
Answer: A guard condition is an early check that rejects or handles an invalid state before the main logic continues.
Answer: Early return exits a method as soon as a condition is satisfied, often reducing nesting.
Answer: An infinite loop is a loop whose termination condition never becomes false or which intentionally runs continuously.
Answer: Ensure loop state changes toward termination and verify the condition and update expression.
Answer: Modifying a collection during foreach can invalidate its enumerator and commonly throws an exception; use an appropriate strategy such as collecting changes first.
Answer: Recursion is when a method calls itself until a base condition is reached.
Answer: It is the condition that stops recursive calls and prevents infinite recursion.
Answer: switch is often clearer when several alternatives depend on one expression or on patterns.
Answer: Pattern matching combines type/value tests with conditions in constructs such as is and switch.
Answer: Relational patterns test values with operators such as <, <=, > and >= in supported pattern contexts.
Answer: Logical patterns combine patterns using and, or and not.
Answer: A local function is a named method declared inside another method and can access appropriate variables from its enclosing scope.
Answer: Deep nesting reduces readability and increases maintenance cost; guard clauses and extracted methods can simplify control flow.
OOPs Concepts
Answer: Encapsulation, abstraction, inheritance and polymorphism are commonly described as the four core OOP principles.
Answer: Encapsulation bundles data and behavior and controls access to internal state through an appropriate public interface.
Answer: Abstraction exposes essential behavior while hiding implementation details.
Answer: Inheritance lets a derived class reuse and specialize accessible members of a base class.
Answer: Polymorphism allows code to work with a base abstraction while the actual derived implementation determines behavior.
Answer: Overloading is commonly associated with compile-time polymorphism; overriding through virtual dispatch is runtime polymorphism.
Answer: A base class is a class from which another class inherits.
Answer: A derived class inherits from a base class and can add or override behavior.
Answer: virtual allows a derived class to provide an overriding implementation of a member.
Answer: override supplies a derived implementation for an inherited virtual or abstract member.
Answer: abstract marks a type or member as requiring further implementation or preventing direct instantiation of the type.
Answer: A sealed override prevents further derived classes from overriding that member.
Answer: Composition builds a type from other objects and is often preferred when reuse does not represent an is-a relationship.
Answer: Inheritance models an is-a relationship; composition models a has-a relationship and often provides looser coupling.
Answer: Dependency injection supplies a class's dependencies from outside rather than constructing them internally.
Answer: It improves testability, flexibility and separation of concerns.
Answer: It is a method that supports runtime overriding by derived classes.
Answer: No. Constructors are not virtual because object construction happens before the object can participate in virtual dispatch.
Answer: No, C# supports single class inheritance, but a class can implement multiple interfaces.
Answer: Yes. An interface can inherit one or more other interfaces.
Answer: Yes. Its constructor can initialize state needed by derived classes.
Answer: No, an abstract class cannot be directly instantiated.
Answer: Modern C# interfaces can contain certain default implementations, but their primary role remains defining a contract.
Answer: Subtypes should be usable wherever their base abstraction is expected without breaking the correctness of the program.
Answer: A class should have a focused responsibility and a reason to change that is as cohesive as practical.
Answer: Software entities should be open for extension but closed for modification.
Answer: Clients should not be forced to depend on methods they do not need.
Answer: High-level policy should depend on abstractions rather than concrete low-level implementations.
Answer: Interfaces can reduce coupling and make implementations replaceable and easier to test.
Answer: A good class has clear responsibility, controlled state, cohesive behavior and dependencies that are explicit and manageable.
Inheritance & Polymorphism
Answer: A class directly inherits from one base class.
Answer: A derived class inherits from another derived class, forming multiple levels.
Answer: Multiple derived classes inherit from the same base class.
Answer: No. A class has only one direct base class.
Answer: A class can implement multiple interfaces.
Answer: base accesses members of the immediate base class or invokes a base constructor.
Answer: this refers to the current object instance and can also be used to call another constructor in the same class.
Answer: Constructor chaining lets one constructor call another constructor using this or a base constructor using base.
Answer: Method hiding uses the new keyword to declare a member that hides an inherited member with the same name.
Answer: new hides an inherited member; override replaces virtual behavior through polymorphic dispatch.
Answer: Upcasting converts a derived object reference to a base class reference and is generally implicit.
Answer: Downcasting converts a base reference to a more specific derived type and may fail if the runtime object is not compatible.
Answer: as attempts a compatible reference conversion and returns null instead of throwing if it cannot convert.
Answer: An explicit cast requests a conversion and throws when a reference conversion is invalid.
Answer: Runtime dispatch selects the overridden implementation based on the actual runtime type of the object.
Answer: They allow derived types to specialize behavior while callers use the base abstraction.
Answer: A base member is not dynamically overridden through normal virtual dispatch; a derived member may instead hide it.
Answer: No, because private members are not accessible to derived classes for overriding.
Answer: No. Static members belong to the type and are not virtual instance members.
Answer: Yes. Properties can be virtual and overridden similarly to methods.
Answer: No. Fields cannot be virtual.
Answer: An abstract method has no implementation in the abstract base type and must be implemented by a suitable non-abstract derived class.
Answer: It prevents further inheritance when the type's design should not be extended.
Answer: A sealed override stops further derived classes from overriding that member.
Answer: Changes to a base class can unexpectedly affect derived classes, which is one reason inheritance should be used carefully.
Answer: Use inheritance when the derived type truly represents a substitutable specialization of the base type.
Answer: Composition is often better when you want to reuse behavior without creating a strong inheritance dependency.
Answer: Code can use an interface reference while the concrete implementation supplies the actual behavior.
Answer: It allows implementations to change without requiring callers to depend on concrete classes.
Answer: A specialized type can inherit common behavior from a base type while adding domain-specific behavior, provided the subtype remains substitutable.
Collections
Answer: A collection stores and manages groups of objects or values.
Answer: An array has fixed length; List is a resizable generic collection.
Answer: List is a generic, dynamically sized collection that supports indexed access.
Answer: Dictionary stores key-value pairs and provides efficient lookup by key under normal hashing assumptions.
Answer: HashSet stores unique elements and provides set operations such as union and intersection.
Answer: Queue represents FIFO ordering: first in, first out.
Answer: Stack represents LIFO ordering: last in, first out.
Answer: IEnumerable focuses on enumeration; ICollection adds collection-oriented capabilities such as Count and modification members depending on the interface.
Answer: IEnumerable generally represents in-memory enumeration; IQueryable represents a query that can be translated by a provider.
Answer: A generic collection is parameterized by type, providing compile-time type safety without many casts.
Answer: Generics improve type safety, reuse and often performance by avoiding unnecessary boxing/casting.
Answer: It is concise syntax for creating a collection and adding initial elements.
Answer: Each key must be unique within a Dictionary; assigning the same key updates its value when using the indexer.
Answer: Dictionary.Add throws an exception if the key already exists.
Answer: Use TryGetValue when a missing key is a normal possibility.
Answer: Capacity is the allocated storage for elements before the list needs to resize.
Answer: Count is the number of stored elements; Capacity is the current allocated capacity.
Answer: A query or iterator may not execute until its results are enumerated.
Answer: ToList materializes a sequence immediately into a List.
Answer: An iterator provides a sequence of values, commonly using yield return.
Answer: yield return produces sequence elements lazily and preserves iterator state between iterations.
Answer: It depends on the element type and nullable annotations/runtime rules; reference-type collections can generally hold null references unless application rules prohibit them.
Answer: Avoid modifying a collection during foreach; iterate over a copy or use collection APIs designed for removal.
Answer: It is a thread-safe dictionary designed for concurrent access scenarios.
Answer: An immutable list cannot be modified in place; operations produce a new collection representing the change.
Answer: Use HashSet when uniqueness and membership/set operations are more important than index-based ordering.
Answer: Use Dictionary when efficient lookup by a unique key is central to the operation.
Answer: Sorting arranges elements according to an ordering, often using Sort or LINQ OrderBy.
Answer: Filtering selects only elements that satisfy a condition, commonly with LINQ Where.
Answer: An exception is an object representing an error or unusual condition that interrupts normal execution.
Answer: try contains code that may throw; catch handles matching exceptions.
Answer: finally runs when control leaves the try/catch structure and is commonly used for cleanup.
Answer: throw raises an exception or rethrows the currently handled exception.
Answer: Inside a catch, bare throw preserves the original exception stack trace; throwing the caught variable as a new throw can reset the stack trace context.
Answer: Yes, multiple catches can handle different exception types; more specific types should be handled before broader ones.
Answer: A custom exception is an application-specific exception type derived from an appropriate exception base class.
Answer: No. Broad catches can hide programming errors. Catch exceptions you can meaningfully handle and let unexpected failures propagate appropriately.
Answer: InnerException preserves the underlying exception that caused or contributed to the current exception.
Answer: Wrap a lower-level exception with contextual information while assigning it as InnerException.
Answer: If an exception is not handled in the current method, it travels up the call stack until a suitable handler is found.
Answer: Under normal control flow finally runs, but abrupt process termination or certain runtime failures can prevent it.
Answer: It can, but returning from finally is strongly discouraged because it can override a pending return or exception.
Answer: It indicates that a null argument was supplied when a method does not accept null.
Answer: It indicates an invalid argument value supplied to a method.
Answer: It indicates that a method call is invalid for the object's current state.
Answer: It occurs when code attempts to access an instance member through a null reference.
Answer: It occurs when an array index is outside the valid bounds.
Answer: It can occur when attempting to retrieve a missing key from a dictionary through an API that throws for absent keys.
Answer: It indicates that an input string is not in the expected format for a conversion or parsing operation.
Answer: It is thrown for an invalid division operation involving zero in contexts where the runtime detects the error.
Answer: Generally no. Expected validation or branching should use normal control flow where practical.
Answer: Log enough context to diagnose the failure while avoiding secrets, passwords and sensitive data.
Answer: Handle them at a boundary where the application can recover, translate the error or provide an appropriate response.
Answer: It means throwing a higher-level exception with the original exception as its inner cause while adding useful context.
Answer: It is a centralized boundary that catches unhandled application errors and converts them into a controlled response/logging action.
Answer: They silently discard failures and make diagnosis and recovery much harder.
Answer: Yes, but callers should understand that object construction failed and resources should be handled appropriately.
Answer: It means ensuring important cleanup occurs even when an operation fails, commonly using finally or using/disposal patterns.
Answer: Validate at boundaries, catch only what you can handle, preserve causes, log useful context and avoid leaking internal details to users.
Delegates & Events
Answer: A delegate is a type-safe reference to a method with a compatible signature.
Answer: A multicast delegate can reference multiple compatible methods and invokes them in invocation order.
Answer: An event provides a controlled publish/subscribe mechanism for notifying subscribers about something that happened.
Answer: A delegate can generally be invoked by its holder; an event restricts invocation so that external code can subscribe/unsubscribe but not raise it directly.
Answer: Action represents a delegate returning void and can accept generic parameters.
Answer: Func represents a delegate that returns a value, with generic parameters describing inputs and the return type.
Answer: Predicate represents a delegate returning bool, commonly used for conditions.
Answer: An anonymous method is a method body assigned to a delegate without declaring a named method.
Answer: A lambda is a concise expression or statement that can represent a delegate or expression tree.
Answer: An expression tree represents code as a data structure and can be inspected or translated by providers.
Answer: Reflection allows code to inspect types, members and metadata at runtime.
Answer: An attribute attaches declarative metadata to program elements.
Answer: Generics allow types and methods to work with type parameters while retaining compile-time type safety.
Answer: A generic constraint restricts which types can be used for a type parameter.
Answer: It restricts T to reference types.
Answer: It restricts T to non-nullable value types.
Answer: It requires T to have an accessible parameterless constructor.
Answer: Covariance allows a more derived generic type argument to be used where a less derived one is expected for compatible output-only generic interfaces/delegates.
Answer: Contravariance allows a less derived type argument where a more derived one is expected for compatible input-only generic interfaces/delegates.
Answer: LINQ provides language-integrated query capabilities over objects and other data sources.
Answer: Many LINQ operators do not execute until the resulting sequence is enumerated.
Answer: An extension method adds callable syntax to an existing type without modifying its source type.
Answer: A partial class lets a type be split across multiple source files and compiled into one type.
Answer: It enables compiler analysis for possible null references and expresses nullability intent in source code.
Answer: A record is a reference or value type designed for data-centric models with value-based equality semantics and concise syntax.
Answer: Classes traditionally emphasize identity and behavior; records are designed for data-centric models and value-oriented equality.
Answer: An init accessor allows a property to be assigned during object initialization but not normally changed afterward.
Answer: Pattern matching checks values against types, constants, properties, relational conditions and combinations of patterns.
Answer: A required member indicates that callers must initialize that member during object creation under the compiler's required-member rules.
Answer: They can improve safety, expressiveness, readability and reduce boilerplate when used appropriately.
LINQ Interview Questions
Answer: LINQ is a set of language-integrated query features and operators for working with data sources.
Answer: Where filters a sequence based on a predicate.
Answer: Select projects each source element into another form.
Answer: Select produces one result per source element; SelectMany flattens nested sequences into one sequence.
Answer: OrderBy sorts elements by a key in ascending order.
Answer: ThenBy adds a secondary ordering after an existing ordering.
Answer: GroupBy groups elements sharing a key.
Answer: Join combines elements from two sequences based on matching keys.
Answer: Any checks whether at least one element satisfies a condition or whether a sequence contains any elements.
Answer: All checks whether every element satisfies a predicate.
Answer: Contains checks whether a sequence contains a specified value according to equality rules.
Answer: First throws if there is no element; FirstOrDefault returns the default value when no element exists.
Answer: Single requires exactly one matching element; SingleOrDefault allows zero or one but throws if more than one exists.
Answer: Count returns an Int32 count; LongCount returns an Int64 count for very large sequences.
Answer: Distinct removes duplicate elements according to equality semantics.
Answer: Skip ignores a specified number of elements.
Answer: Take returns a specified number of elements from the beginning.
Answer: A query can be built without immediately executing it; execution occurs when enumerated.
Answer: Operators such as ToList, ToArray and many aggregate operations force query evaluation.
Answer: IEnumerable LINQ executes delegates against enumerated objects; IQueryable can build expression trees that a provider may translate.
Answer: Projection transforms each source element into a different shape using Select.
Answer: An anonymous type is a compiler-generated type used to hold a set of read-only properties for local use.
Answer: Query syntax is SQL-like C# syntax for writing certain LINQ queries.
Answer: Method syntax uses extension methods such as Where, Select and OrderBy.
Answer: Most LINQ operators produce results without modifying the original source; mutations depend on explicitly executed code or collection operations.
Answer: Aggregate operators combine sequence values into a single result, such as Sum, Min, Max, Average or Aggregate.
Answer: Aggregate applies an accumulator function across a sequence to produce one result.
Answer: ToDictionary materializes a sequence into a Dictionary using selected key/value selectors and requires unique keys.
Answer: AsEnumerable changes the static view to IEnumerable so subsequent LINQ operators use Enumerable methods.
Answer: Filter early, project only needed data, avoid repeated enumeration and materialize only when necessary.
Async / Await Interview Questions
Answer: Asynchronous programming allows work to proceed without blocking the calling thread while an operation is incomplete.
Answer: Task represents an asynchronous operation that may complete successfully, fault or be canceled.
Answer: async enables await within a method and causes compatible return patterns for asynchronous methods.
Answer: await asynchronously waits for an awaitable operation and resumes the method when it completes without blocking the current thread in the normal async pattern.
Answer: Task represents completion without a result; Task represents asynchronous completion with a result of type T.
Answer: async void is mainly intended for event handlers; application/library methods should generally return Task or Task so callers can await and observe failures.
Answer: CancellationToken provides cooperative cancellation signaling for asynchronous or long-running operations.
Answer: It creates and controls a cancellation token and can request cancellation.
Answer: ConfigureAwait controls whether an awaited continuation attempts to resume on a captured context where applicable.
Answer: WhenAll creates a task that completes when all supplied tasks complete.
Answer: WhenAny completes when any supplied task completes.
Answer: Awaiting operations one after another is sequential; starting independent operations and awaiting WhenAll can allow them to overlap.
Answer: Not necessarily. Async I/O often frees the current thread while waiting; thread-pool work is different from asynchronous I/O.
Answer: A deadlock can occur when synchronous blocking and captured contexts prevent asynchronous continuations from progressing.
Answer: They synchronously block and can cause deadlocks or thread-pool starvation in some environments.
Answer: Exceptions from awaited Tasks can be observed through try/catch around await.
Answer: The task completes in a faulted state and its exception is observed when awaited or inspected.
Answer: The operation periodically observes a token and stops gracefully when cancellation is requested.
Answer: Yes. ValueTask can reduce allocations in suitable high-performance scenarios, but it should be used when its trade-offs are understood.
Answer: It represents an asynchronously produced sequence that can be consumed with await foreach.
Answer: await foreach asynchronously enumerates an IAsyncEnumerable sequence.
Answer: It can avoid depending on a captured synchronization context in library-style code where returning to that context is unnecessary.
Answer: CPU-bound work is limited primarily by processor computation rather than waiting on I/O.
Answer: I/O-bound work spends significant time waiting for external operations such as network, database or file I/O.
Answer: No. Async is most valuable for non-blocking asynchronous operations; CPU-bound work may need parallelism or background execution when appropriate.
Answer: Task.Run schedules CPU-oriented work on the thread pool; it is not a general replacement for naturally asynchronous I/O APIs.
Answer: It is work started without awaiting its completion; it can cause unobserved failures and lifetime problems, so it should be used only with an appropriate hosted/background mechanism.
Answer: Start the tasks first, then await Task.WhenAll when their results are all required.
Answer: Adding async/await without a need can add overhead and obscure the actual asynchronous operation.
Answer: Use async all the way through I/O paths, propagate cancellation where appropriate, observe failures and avoid synchronous blocking.
Scenario Based C# Interview Questions
Answer: Measure where time is spent: network latency, database calls, external APIs, serialization, locks and CPU work before changing code.
Answer: Check logs, exception details, request correlation information, recent deployments, dependencies and reproducibility while avoiding sensitive data exposure.
Answer: Identify which reference is null using debugging/logging and trace how the null reached that point rather than simply adding broad null checks.
Answer: Look for repeated database/API calls, expensive operations inside the loop, unnecessary allocations and algorithmic complexity.
Answer: Inspect generated SQL/query shape, number of rows, repeated calls, indexes and whether unnecessary data is being loaded.
Answer: Use idempotency or deduplication based on the operation and a reliable request key.
Answer: Validate input at the boundary and use clear validation rules before invoking core operations.
Answer: Use timeouts, appropriate retries for transient failures, logging, fallback behavior where valid and clear failure handling.
Answer: Retry transient failures where the operation is safe to retry; use bounded attempts and backoff rather than retrying every exception.
Answer: Separate responsibilities into cohesive methods/services, clarify data flow and add tests before and after refactoring.
Answer: Separate business logic from infrastructure, inject dependencies and avoid hard-coded external calls.
Answer: If membership/key lookup dominates, consider a HashSet or Dictionary with appropriate equality semantics.
Answer: Choose a suitable synchronization or concurrent collection strategy based on access patterns and required guarantees.
Answer: Collect evidence with profiling/diagnostics, inspect object retention, caches, subscriptions, large allocations and disposal of unmanaged resources.
Answer: Use a disposal pattern such as using so the stream is released even when an operation fails.
Answer: The application may continue in an invalid state and diagnostics are lost.
Answer: Include useful operation/context identifiers and the exception details while excluding secrets and unnecessary personal data.
Answer: Use guard clauses, extracted methods, strategy/polymorphism or data-driven rules when those alternatives improve clarity.
Answer: Identify separate responsibilities and extract cohesive components with clear boundaries.
Answer: It tightly couples the service to concrete implementations and makes testing and replacement harder.
Answer: Dependencies are supplied externally, making the class easier to test and configure.
Answer: Accept a CancellationToken, pass it to cancellable operations and stop cooperatively when cancellation is requested.
Answer: Start appropriate operations without unnecessary sequential waits and await them together with controlled concurrency if needed.
Answer: Materialize once when repeated enumeration is intended and avoid repeated expensive database or computation queries.
Answer: Await the task inside a try/catch so the exception can be observed and handled at the appropriate boundary.
Answer: Return a safe client-facing error while logging diagnostic details internally.
Answer: Use clear naming, cohesive components, tests, consistent error handling, dependency boundaries and appropriate abstractions.
Answer: Capture correlation IDs, structured logs, timing and relevant state so the failing path can be reconstructed without relying only on local reproduction.
Answer: Measure first, identify the bottleneck, change the smallest effective area and verify the improvement with repeatable metrics.
Welcome to Help Box—your ultimate destination for clear, reliable, and hassle-free tech solutions.
Whether you are trying to fix a stubborn system error, figure out a new digital tool, or looking for step-by-step tech guides,searching quiz and ebooks, Help Box cuts through the confusion to give you straightforward answers.
No comments:
Post a Comment