CSharp Interview Questions and Answers
What is C#?
- C# (pronounced "C sharp") is a modern, object-oriented, and type-safe programming language developed by Microsoft within the .NET framework. It is designed to be a simple, powerful, and versatile language for building a wide range of applications.
What is the .NET Framework?
- The .NET Framework is a software framework developed by Microsoft that provides a large class library (Framework Class Library - FCL) and a runtime environment (Common Language Runtime - CLR) for developing and running applications. It was primarily designed for Windows development.
What is .NET Core?
- .NET Core was a cross-platform, open-source, and modular implementation of the .NET platform. It was designed to be more lightweight and flexible than the .NET Framework, supporting Windows, macOS, and Linux. It has since evolved into the unified .NET platform (starting with .NET 5).
What is the difference between .NET Framework and .NET Core (or modern .NET)?
- Platform: .NET Framework is Windows-only. .NET Core (and modern .NET) is cross-platform (Windows, macOS, Linux, etc.).
- Open Source: .NET Framework is proprietary. .NET Core and modern .NET are open source.
- Deployment: .NET Framework requires the framework to be installed on the target machine. .NET Core and modern .NET allow for self-contained deployments.
- Architecture: .NET Core and modern .NET have a more modular architecture.
What is the Common Language Runtime (CLR)?
- The CLR is the runtime environment for .NET applications. It is responsible for executing code, managing memory (Garbage Collection), handling exceptions, providing security, and performing Just-In-Time (JIT) compilation.
What is the Common Type System (CTS)?
- The CTS is a standard that defines how types are declared, used, and managed in the .NET ecosystem. It ensures type safety across different .NET languages.
What is the Common Language Specification (CLS)?
- The CLS is a set of rules and guidelines that define the features that .NET languages must support to be interoperable with each other. Languages that adhere to the CLS are considered "CLS-compliant."
What is the difference between managed and unmanaged code?
- Managed Code: Code that is executed and managed by the CLR. The CLR handles memory allocation, garbage collection, and other runtime services. C# code is typically managed code.
- Unmanaged Code: Code that is executed outside the control of the CLR. Memory management and other services must be handled manually. Examples include code written in C++ or interacting directly with the operating system.
What is Boxing and Unboxing?
- Boxing: The process of converting a value type (like
int
) to a reference type (likeobject
). This involves allocating memory on the heap and copying the value. - Unboxing: The process of converting an
object
type back to a value type. This involves checking the object's type and copying the value from the heap to the stack. Boxing and unboxing can incur performance overhead.
Explain Value Types and Reference Types.
- Value Types: Store their data directly on the stack (or inline within their containing type). Copies create independent instances. Examples:
int
,float
,bool
,char
,structs
,enums
. - Reference Types: Store a reference (memory address) to their data on the heap. Copies share the same underlying data. Examples:
class
,interface
,delegate
,string
,array
.
What is the difference between const
and readonly
?
const
: Used for fields whose value is a compile-time constant. Must be initialized at the time of declaration. Implicitly static.readonly
: Used for fields that can be initialized either at the time of declaration or in the constructor of the class. Their value cannot be changed after the constructor finishes. Not implicitly static.
What are access modifiers in C#?
-
Access modifiers control the accessibility of types and type members.
public
: Accessible from anywhere.private
: Accessible only within the defining class or struct.protected
: Accessible within the defining class and by derived classes.internal
: Accessible only within the same assembly.protected internal
: Accessible within the same assembly OR by derived classes in other assemblies.private protected
(C# 7.2+): Accessible within the defining class OR by derived classes in the same assembly.
What is Encapsulation?
- Encapsulation is the bundling of data (fields) and the methods that operate on that data within a single unit (a class). It also involves data hiding, where the internal state of an object is hidden from the outside, and access is controlled through public properties or methods.
What is Abstraction?
- Abstraction is the process of hiding complex implementation details and showing only the essential features of an object. It focuses on what an object does rather than how it does it. Abstract classes and interfaces are used to achieve abstraction.
What is Inheritance?
- Inheritance is a mechanism that allows a new class (derived class) to inherit properties (fields, methods, events, etc.) from an existing class (base class). It promotes code reusability and establishes an "is-a" relationship. C# supports single inheritance for classes.
What is Polymorphism?
- Polymorphism means "many forms." In C#, it allows objects of different classes to respond to the same method call in their own specific way. It enables a single interface to be used for a variety of types.
Explain Method Overloading and Method Overriding.
- Method Overloading: Defining multiple methods with the same name but different parameter lists (different number of parameters, different types of parameters, or both) within the same class. (Compile-time polymorphism).
- Method Overriding: Providing a new implementation in a derived class for a method that is already defined in the base class. The method signature must be the same. The base class method must be marked as
virtual
, and the derived class method must be marked asoverride
. (Runtime polymorphism).
What is a Constructor?
- A constructor is a special member method of a class that is automatically called when an object of that class is created. Its primary purpose is to initialize the object's state. It has the same name as the class and no return type.
What is a Destructor (Finalizer)?
- A destructor (more accurately called a finalizer in C#) is a special method that is called by the Garbage Collector just before an object is collected. Its purpose is to release unmanaged resources held by the object. Destructors are non-deterministic and should generally be avoided in favor of the
IDisposable
interface andusing
statements.
Explain the different types of constructors.
- Default Constructor: A parameterless constructor. If no constructor is defined, the compiler provides a public default constructor for classes.
- Parameterized Constructor: Takes one or more parameters to initialize the object with specific values.
- Copy Constructor: A constructor that creates a new object as a copy of an existing object of the same class.
- Static Constructor: A parameterless constructor that is called automatically before the first instance of the class is created or any static members are accessed. Used to initialize static members.
What is the difference between a Class and a Struct?
- Class: A reference type. Stored on the heap. Supports inheritance. Can have a default constructor (provided by compiler). Can be null.
- Struct: A value type. Stored on the stack (or inline). Does not support inheritance. Does not have an implicitly generated parameterless constructor (unless defined explicitly in C# 10+). Cannot be null (unless using nullable types). Generally used for small, simple data structures.
What is an Abstract Class?
- An abstract class is a class that cannot be instantiated directly. It is designed to be a base class for other classes. Abstract classes can contain both abstract members (without implementation) and concrete members (with implementation).
What is an Interface?
- An interface defines a contract that a class or struct must implement. It contains only declarations of members (methods, properties, events, indexers) but no implementation. A class can implement multiple interfaces.
What is the difference between an Abstract Class and an Interface?
- Abstract Class: Can have abstract and concrete members. Can have fields and constructors. A class can inherit from only one abstract class. Used for "is-a" relationships where there's a common base implementation.
- Interface: Contains only declarations (no implementation before C# 8). Cannot have fields or constructors (except for default interface methods in C# 8+). A class can implement multiple interfaces. Used for "can-do" or "has-a capability" relationships.
What is a Sealed Class?
- A sealed class is a class that cannot be inherited from. The
sealed
keyword prevents further derivation.
What is the purpose of the this
keyword?
- The
this
keyword refers to the current instance of the class. It is used to access members of the current object, especially when there are name conflicts or when passing the current object as an argument.
What is the purpose of the base
keyword?
- The
base
keyword is used in a derived class to access members (constructors, methods, properties) of its base class.
What is the static
keyword used for?
- The
static
keyword makes a member (field, property, method, constructor, event) belong to the type itself rather than to a specific instance of the type. There is only one copy of a static member shared among all instances (and accessible even if no instances exist). Static members are accessed using the type name (e.g.,ClassName.StaticMethod()
).
What is a Static Class?
- A static class is a class that cannot be instantiated and contains only static members. It is implicitly sealed and abstract. Static classes are often used for utility classes or helper functions.
What is a Property?
- A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. It consists of a getter (for reading) and/or a setter (for writing). Properties provide controlled access and enable encapsulation.
What is an Indexer?
- An indexer allows objects of a class or struct to be indexed like an array (using square brackets
[]
). It is similar to a property but accessed using an index instead of a name.
What is a Delegate?
- A delegate is a type-safe function pointer. It holds a reference to a method (or multiple methods in the case of multicast delegates) with a specific signature and return type. Delegates are used for event handling, callbacks, and asynchronous operations.
What is an Event?
- An event is a member that enables an object to notify other objects when something of interest happens. Events are based on the observer pattern and use delegates to define the signature of the event handlers.
What is the difference between a Delegate and an Event?
- A delegate is a type that defines a method signature. An event is a mechanism that uses delegates to provide notifications. Events encapsulate delegates and provide controlled access to adding and removing event handlers.
What is Exception Handling?
- Exception handling is a mechanism to deal with runtime errors or exceptional conditions in a structured way. It involves the
try
,catch
, andfinally
blocks.
Explain the try
, catch
, and finally
blocks.
try
: A block of code that might throw an exception.catch
: A block of code that handles a specific type of exception thrown in the precedingtry
block. You can have multiplecatch
blocks.finally
: A block of code that is always executed, regardless of whether an exception occurred or was caught. It is typically used for cleanup operations (e.g., closing files, releasing resources).
What is the purpose of the using
statement?
- The
using
statement is used to ensure that an object that implements theIDisposable
interface is properly disposed of (itsDispose()
method is called) when it goes out of scope, even if an exception occurs. This helps prevent resource leaks.
What is the IDisposable
interface?
- The
IDisposable
interface defines a single method,Dispose()
, which is used to release unmanaged resources held by an object. Classes that manage unmanaged resources should implement this interface.
What is Garbage Collection (GC)?
- Garbage Collection is an automatic memory management process in the CLR. The GC automatically reclaims memory occupied by objects that are no longer reachable (referenced) by the application, preventing memory leaks.
What is the difference between Dispose()
and a Finalizer (Destructor)?
Dispose()
: Explicitly called by the programmer (often via ausing
statement) to release unmanaged resources immediately. Deterministic cleanup.- Finalizer (Destructor): Called non-deterministically by the GC just before an object is collected. Used for unmanaged resource cleanup but should be avoided for managed resources.
What are Generics?
- Generics allow you to write type-safe and reusable code. They enable you to define classes, interfaces, and methods with placeholder types (type parameters) that are specified when the type or method is used. This avoids the need for boxing/unboxing and provides compile-time type checking.
What is LINQ (Language Integrated Query)?
- LINQ is a set of technologies in C# that provides a consistent way to query data from various sources (like collections, databases, XML) using a syntax similar to SQL. It supports querying in-memory objects (LINQ to Objects), databases (LINQ to SQL, Entity Framework), and XML (LINQ to XML).
Explain Query Syntax and Method Syntax in LINQ.
- Query Syntax: Uses a declarative syntax with keywords like
from
,where
,select
, etc., similar to SQL. (e.g.,from item in collection where condition select item;
). - Method Syntax: Uses extension methods provided by LINQ (e.g.,
Where()
,Select()
). (e.g.,collection.Where(item => condition).Select(item => item);
). Query syntax is often translated into method syntax by the compiler.
What is Deferred Execution in LINQ?
- Deferred execution means that a LINQ query is not executed immediately when it is defined. The query is executed only when the results are actually needed (e.g., when iterating over the results using a
foreach
loop or calling methods likeToList()
orToArray()
).
What is an Extension Method?
- An extension method allows you to add new methods to existing types without modifying the original type's source code. They are static methods defined in a static class, with the first parameter preceded by the
this
keyword to indicate the type being extended.
What is an Anonymous Type?
- An anonymous type is a temporary, implicitly typed class created by the compiler to store a set of properties. They are often used with LINQ queries to project a subset of properties from a collection.
What is the difference between var
and explicit type declaration?
var
: The compiler infers the type of the variable from its initializer. Can only be used for local variables. The type is still strongly typed at compile time.- Explicit type declaration: You explicitly specify the type of the variable.
What are Nullable Types?
- Nullable types allow value types to represent the value
null
in addition to their normal range of values. They are declared by appending a question mark to the value type (e.g.,int?
,bool?
). They are instances of theNullable
struct.
Explain the Null-Coalescing Operator (??
).
- The null-coalescing operator (
??
) provides a default value for a nullable type or reference type if it is null. It evaluates the left-hand operand; if it's not null, it returns the left-hand operand's value; otherwise, it evaluates and returns the right-hand operand.
Explain the Null-Conditional Operator (?.
and ?[]
).
- The null-conditional operator (
?.
for member access,?[]
for element access) provides a shorthand for performing a null check before accessing a member or element. If the operand is null, the expression evaluates to null without throwing aNullReferenceException
.
What is Asynchronous Programming in C#?
- Asynchronous programming allows an application to perform operations (like I/O or CPU-bound tasks) without blocking the main thread, improving responsiveness and scalability. C# provides the Task-based Asynchronous Pattern (TAP) with the
async
andawait
keywords.
Explain the async
and await
keywords.
async
: Used to mark a method as asynchronous. An async method can contain one or moreawait
expressions.await
: Used within an async method to pause the execution of the method until an awaited asynchronous operation (typically aTask
orTask
) completes. Control is returned to the caller, and the thread is not blocked.
What is a Task
and Task
?
Task
: Represents an asynchronous operation that does not return a value.Task
: Represents an asynchronous operation that returns a value of typeTResult
.
What is the difference between multithreading and asynchronous programming?
- Multithreading: Involves running multiple threads concurrently. Often used for CPU-bound tasks to utilize multiple processor cores. Requires careful synchronization to avoid race conditions.
- Asynchronous Programming: Focuses on not blocking the current thread while waiting for an operation to complete. Often used for I/O-bound tasks (like network requests, file operations) to free up the thread for other work.
What is Synchronization in multithreading?
- Synchronization is the process of coordinating the execution of multiple threads to ensure that shared resources are accessed in a controlled manner, preventing race conditions and data corruption. C# provides synchronization primitives like
lock
,Mutex
,Semaphore
, etc.
Explain the lock
keyword.
- The
lock
keyword is used to acquire a mutual-exclusion lock for a given object, ensuring that only one thread can enter the protected code block at a time. It is a convenient way to protect shared resources from concurrent access.
What is a Race Condition?
- A race condition occurs when the outcome of a program depends on the unpredictable timing of multiple threads accessing and modifying shared data.
What is a Deadlock?
- A deadlock is a situation where two or more threads are blocked indefinitely, waiting for each other to release resources that they need.
What are Collections in C#?
- Collections are classes that provide flexible ways to store and manage groups of objects. The .NET Framework provides various collection classes in namespaces like
System.Collections
andSystem.Collections.Generic
.
What are some common generic collection classes?
List
: A dynamic array (resizable).Dictionary
: Stores key-value pairs, optimized for fast lookups by key.HashSet
: Stores unique elements, optimized for fast membership testing.Queue
: Represents a first-in, first-out (FIFO) collection.Stack
: Represents a last-in, first-out (LIFO) collection.
What is the difference between ArrayList
and List
?
ArrayList
(non-generic): Can store elements of any type (object
). Requires boxing/unboxing for value types, leading to performance overhead and runtime type errors.List
(generic): Is type-safe. Stores elements of a specific typeT
, avoiding boxing/unboxing and providing compile-time type checking. Generally preferred.
What is Reflection?
- Reflection is the ability of a program to examine and modify its own metadata (information about types, members, etc.) at runtime. It allows you to inspect types, create instances of types, and invoke members dynamically.
What are Attributes?
- Attributes are a way to add declarative information (metadata) to code elements (assemblies, types, members, etc.). They are used by the compiler, runtime, and tools to provide additional information or modify behavior. Examples:
[Serializable]
,[Obsolete]
,[Test]
.
What is Serialization?
- Serialization is the process of converting an object's state into a format (like a sequence of bytes or a string) that can be stored or transmitted.
What is Deserialization?
- Deserialization is the process of converting serialized data back into an object.
What are Tuples? (C# 7+)
- Tuples are lightweight data structures that can group multiple elements of potentially different types. Value tuples (introduced in C# 7) are value types and provide a more efficient alternative to the older
Tuple
class.
What is Pattern Matching? (C# 7+)
- Pattern matching is a set of language features that allows you to test if an object has a certain "shape" and extract data from it. It enhances
is
expressions andswitch
statements.
What are Records? (C# 9+)
- Records are a new reference type (or value type with
record struct
in C# 10+) designed for scenarios where you want an immutable data carrier with value-based equality. They provide concise syntax for defining properties, constructors, and methods for comparison and immutability.
Explain the concept of immutability.
- Immutability means that the state of an object cannot be changed after it is created. Immutable objects are thread-safe and can simplify reasoning about code.
What is the init
keyword? (C# 9+)
- The
init
keyword is used with properties to create "init-only" setters. These properties can only be set during object initialization (either through a constructor or an object initializer). Once the object is initialized, the property cannot be changed.
What are Top-Level Statements? (C# 9+)
- Top-level statements allow you to write executable code directly in a
.cs
file without explicitly defining aProgram
class andMain
method. This simplifies writing small programs and scripts.
What are Global Using Directives? (C# 10+)
- Global using directives (
global using Namespace;
) allow you to specifyusing
directives once in a project file or a single source file, and they apply to all files in the project. This reduces boilerplate code.
What are File-Scoped Namespaces? (C# 10+)
- File-scoped namespaces (
namespace MyNamespace;
) allow you to declare a namespace that applies to the entire file without nesting the code within curly braces. This simplifies the structure of many source files.
What is the difference between IEnumerable
and IQueryable
? (LINQ)
IEnumerable
: Represents a collection that can be iterated over. Queries are executed in memory.IQueryable
: Represents a query that can be executed against a data source (like a database). Queries are translated into the data source's native query language (e.g., SQL) and executed on the data source. Offers better performance for large data sets as filtering and sorting happen on the server.
What is Entity Framework Core (EF Core)?
- EF Core is a modern, lightweight, extensible, and cross-platform Object-Relational Mapper (ORM) for .NET. It enables developers to work with a database using .NET objects, eliminating the need for most of the data-access code they would otherwise need to write.
What is Dependency Injection (DI)?
- Dependency Injection is a design pattern where an object receives the objects it depends on (its dependencies) from an external source rather than creating them itself. This promotes loose coupling, testability, and maintainability.
What is Inversion of Control (IoC)?
- Inversion of Control is a principle where the flow of control in a program is inverted. Instead of the program controlling the execution flow, an external framework or container takes control and calls into the program's code when needed. DI is a form of IoC.
What is the difference between Method Overloading and Operator Overloading?
- Method Overloading: Defining multiple methods with the same name but different parameter lists.
- Operator Overloading: Defining how C# operators (like
+
,-
,==
) should behave when applied to instances of user-defined types (classes or structs).
What is the purpose of the sealed
keyword on a method?
- When applied to an
override
method in a derived class, thesealed
keyword prevents further overriding of that method in classes derived from that class.
What is the difference between is
and as
operators?
is
: Checks if an object is compatible with a given type and returns a boolean. Often used with pattern matching for type testing and casting.as
: Attempts to cast an object to a specified type. If the cast is successful, it returns the casted object; otherwise, it returnsnull
. Can only be used with reference types and nullable value types.
What is the purpose of the typeof
operator?
- The
typeof
operator is used to obtain theSystem.Type
object for a given type at compile time.
What is the purpose of the nameof
operator? (C# 6+)
- The
nameof
operator gets the string name of a variable, type, or member. It is useful for avoiding magic strings, especially when dealing with reflection, logging, or property change notifications.
What is the purpose of the checked
and unchecked
keywords?
checked
: Enables overflow checking for arithmetic operations on integer types. If an operation results in an overflow, aSystem.OverflowException
is thrown.unchecked
: Disables overflow checking. Overflowed results are truncated. This is the default behavior.
What is the purpose of the fixed
statement in unsafe code?
- In unsafe code, the
fixed
statement is used to temporarily "fix" the location of a variable (like an array or a string) in memory, preventing the Garbage Collector from moving it during its execution. This allows you to obtain a pointer to the variable.
What is the difference between string
and StringBuilder
?
string
: Immutable. Every modification (like concatenation) creates a new string object in memory. Can be inefficient for frequent string manipulation.StringBuilder
: Mutable. Allows efficient modification of strings without creating new objects for each change. Preferred for building strings incrementally or performing frequent modifications.
What is the Global Assembly Cache (GAC)?
- The GAC is a machine-wide repository for strong-named assemblies. Assemblies stored in the GAC are available to all applications running on the machine. It helps avoid DLL hell and enables side-by-side execution of different versions of the same assembly. (Less relevant in modern .NET compared to .NET Framework).
What is a Strong Name Assembly?
- A strong-named assembly is an assembly that has a unique identity. It includes the assembly's name, version number, culture information, public key, and a digital signature. Strong naming provides versioning, naming uniqueness, and integrity checks.
What is a Delegate? (revisited)
- A delegate is a type that represents references to methods with a particular parameter list and return type. Delegates are used for event handling, callback mechanisms, and anonymous methods.
What is the difference between Action
, Func
, and Predicate
delegates?
Action
: A delegate that points to a method that takes zero or more parameters but does not return a value (void
).Func
: A delegate that points to a method that takes zero or more parameters and returns a value. The last type parameter specifies the return type.Predicate
: A delegate that points to a method that takes a single parameter and returns a boolean value. Often used for filtering collections.
What is a Lambda Expression?
- A lambda expression is a concise way to create an anonymous method (a method without a name). They are often used with LINQ and delegates.
What is the difference between a Lambda Expression and an Anonymous Method?
- Lambda expressions are a more concise syntax for anonymous methods (introduced in C# 3.0). Anonymous methods (introduced in C# 2.0) use the
delegate
keyword. Lambda expressions are generally preferred.
What is Closure?
- A closure is a function or method that "closes over" the variables from its surrounding scope. Anonymous methods and lambda expressions can form closures, capturing local variables from the context where they are defined.
What is the difference between IEnumerable
and ICollection
?
IEnumerable
: Represents a collection that can be iterated over. Provides a basic iterator.ICollection
: Inherits fromIEnumerable
and adds methods for adding, removing, counting, and checking for the presence of elements. Represents a collection that can be modified.
What is the difference between ICollection
and IList
?
ICollection
: Represents a collection that can be modified.IList
: Inherits fromICollection
and adds methods for accessing elements by index, inserting, and removing elements at specific positions. Represents a collection that is ordered and can be accessed by index.
What is the difference between IList
and List
?
IList
: An interface that defines the contract for a list.List
: A concrete class that implements theIList
interface.
What is the purpose of the yield return
statement?
- The
yield return
statement is used in iterator blocks (methods that returnIEnumerable
,IEnumerable
,IEnumerator
, orIEnumerator
) to return elements one at a time. It allows for lazy evaluation and avoids loading the entire collection into memory at once.
What is the difference between throw ex;
and throw;
?
throw ex;
: Throws a new exception object, losing the original call stack information.throw;
: Rethrows the currently caught exception, preserving the original call stack information. This is generally preferred when rethrowing an exception.
What is the purpose of the using static
directive? (C# 6+)
- The
using static
directive allows you to import the static members of a type directly into the current scope, so you can call them without qualifying them with the type name (e.g.,WriteLine("Hello");
instead ofSystem.Console.WriteLine("Hello");
).
What is the purpose of the ?
operator in nullable types? (revisited)
- The
?
operator is used to declare a nullable value type (e.g.,int?
). It is shorthand forSystem.Nullable
.
What is the purpose of the =>
operator (lambda operator and expression body)? (revisited)
- Used in lambda expressions to separate the parameters from the expression body.
- Used in expression-bodied members (methods, properties, constructors, etc.) to provide a concise syntax for members that consist of a single expression.
What is the purpose of the ::
operator (namespace alias qualifier)?
- The
::
operator is used to access a member of a namespace alias. It is useful when you have conflicting names between different namespaces.
What is the purpose of the stackalloc
keyword in unsafe code?
- In unsafe code, the
stackalloc
keyword is used to allocate memory on the stack. Memory allocated on the stack is automatically deallocated when the method returns, which can be more efficient than heap allocation for small, short-lived buffers.
What is the purpose of the checked
and unchecked
keywords? (revisited)
checked
: Enforces overflow checking for integer arithmetic.unchecked
: Disables overflow checking (default).
What is the difference between a value type and a reference type regarding assignment?
- Value Type: Assignment copies the value. Two variables hold independent copies of the data.
- Reference Type: Assignment copies the reference (memory address). Two variables point to the same data on the heap.
What is the purpose of the out
keyword?
- The
out
keyword is used with method parameters to indicate that the parameter is passed by reference, and the method is expected to assign a value to the parameter before returning. The variable passed as anout
argument does not need to be initialized before the call.
What is the purpose of the ref
keyword?
- The
ref
keyword is used with method parameters to indicate that the parameter is passed by reference. Changes made to the parameter inside the method affect the original argument. The variable passed as aref
argument must be initialized before the call.
What is the difference between out
and ref
?
out
: Parameter must be assigned a value inside the method. Argument does not need to be initialized before the call.ref
: Parameter does not need to be assigned a value inside the method. Argument must be initialized before the call.
What is the purpose of the params
keyword?
- The
params
keyword is used with the last parameter of a method to indicate that it is a parameter array. It allows the method to accept a variable number of arguments of a specific type. The arguments are treated as an array inside the method.
What is the difference between an abstract method and a virtual method?
- Abstract Method: Declared in an abstract class, has no implementation in the base class, and must be implemented by derived non-abstract classes using the
override
keyword. - Virtual Method: Declared in a base class, has an implementation in the base class, and can be optionally overridden by derived classes using the
override
keyword.
What is the purpose of the new
keyword when overriding a method?
- Using the
new
keyword with a method in a derived class hides a base class member with the same name. It does not override the base class method. This should be used with caution as it can lead to confusion.
What is the purpose of the sealed
keyword on a class? (revisited)
- Prevents other classes from inheriting from this class.
What is the purpose of the static
constructor? (revisited)
- Used to initialize static members of a class. Called automatically once per type, before any instance is created or any static members are accessed.
What is the difference between a field and a property? (revisited)
- Field: A variable that stores data directly. Typically kept private for encapsulation.
- Property: Provides controlled access (get/set) to a field, allowing for validation, computed values, etc.
What is the purpose of the using
directive at the top of a file? (revisited)
- Imports namespaces, making the types within those namespaces accessible without full qualification.
What is the purpose of the checked
and unchecked
statements/expressions?
- Allows you to control overflow checking within a specific block of code or expression, overriding the default compiler setting.
What is the purpose of the is
operator with type patterns? (C# 7+) (revisited)
- Combines type checking and assignment.
if (obj is MyType myVar) { ... }
checks ifobj
is of typeMyType
and, if so, assigns it to a new variablemyVar
.
What is the purpose of the switch
expression? (C# 8+)
- A more concise syntax for switch statements that returns a value based on the input.
What is the purpose of the using
declaration? (C# 8+) (revisited)
- A shorthand for the
using
statement. The resource is disposed at the end of the current scope (method, block, etc.).
What is the purpose of the null-coalescing assignment
operator (??=
)? (C# 8+) (revisited)
- Assigns the right-hand operand to the left-hand operand only if the left-hand operand is null.
What is the purpose of the Indices and Ranges
feature? (C# 8+)
- Provides a more convenient way to access elements in sequences using indices from the end (
^
operator) and ranges (..
operator).
What is the purpose of the Target-typed new
expression? (C# 9+) (revisited)
- Allows you to omit the type name when creating a new object if the type can be inferred from the context (e.g.,
MyClass obj = new();
).
What are Positional Records? (C# 9+)
- A concise syntax for defining records by listing the properties in the parentheses after the record name. The compiler automatically generates properties, a constructor, and methods for equality and deconstruction.
What is the purpose of the with
expression? (C# 9+)
- Used with records (and structs in C# 10+) to create a new instance with some properties modified, while keeping the original instance immutable.
What is the difference between ==
and Equals()
?
-
==
operator:- For value types, it compares the values.
- For reference types, by default, it compares the references (checks if they point to the same object in memory). Can be overloaded.
-
Equals()
method:- For value types, the default implementation compares the values. Can be overridden.
- For reference types, the default implementation in
object
compares references. Should be overridden in custom classes to provide value-based comparison if needed.
What is the purpose of the GetHashCode()
method?
- The
GetHashCode()
method returns an integer hash code for an object. It is used by hash-based collections (likeDictionary
andHashSet
) to efficiently store and retrieve objects. If two objects are considered equal (byEquals()
), they must have the same hash code.
What is the difference between const
and static readonly
?
const
: Compile-time constant. Value must be known at compile time. Implicitly static.static readonly
: Runtime constant. Value can be initialized at runtime (in the static constructor). Static, but its value can be determined later.
What is a Singleton design pattern? How can you implement it in C#?
- The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. Implementation typically involves a private constructor and a public static property or method that returns the single instance, often with lazy initialization.
What is the difference between an abstract class and a sealed class?
- Abstract class: Cannot be instantiated, designed for inheritance.
- Sealed class: Cannot be inherited from, prevents further derivation.
What is the purpose of the dynamic
keyword? (C# 4+)
- The
dynamic
keyword bypasses compile-time type checking and defers it to runtime. Operations on adynamic
object are resolved at runtime. This is useful for interoperability with dynamic languages or COM objects.
What is the difference between early binding and late binding?
- Early Binding (Compile-time binding): The compiler resolves method calls and member access at compile time. This is the default behavior in C# and provides performance benefits and type safety.
- Late Binding (Runtime binding): Method calls and member access are resolved at runtime. Used with reflection or the
dynamic
keyword. Less performant and less type-safe than early binding.
What is the purpose of the volatile
keyword?
- The
volatile
keyword indicates that a field might be modified by multiple threads executing concurrently. It prevents the compiler and runtime from performing certain optimizations that could lead to unexpected behavior in multithreaded scenarios (e.g., caching the value in a register).
What is the difference between stack
and heap
memory?
- Stack: Used for storing value types, method parameters, and local variables. Memory allocation and deallocation are fast. Follows a LIFO (Last-In, First-Out) order. Limited size.
- Heap: Used for storing reference types (objects). Memory allocation and deallocation are slower due to Garbage Collection. Larger size.
What is the purpose of the yield return
statement? (revisited)
- Used to create iterators, allowing a method to return a sequence of values one by one, lazily.
What is the purpose of the System.Text.Json
library? (.NET Core/5+)
- A high-performance JSON serialization and deserialization library provided in modern .NET.
What is the purpose of the System.Xml.Serialization
library?
- Used for serializing and deserializing objects to and from XML.
What is the purpose of the System.IO
namespace?
- Provides types for working with files, directories, and streams.
What is the purpose of the System.Net.Http.HttpClient
class?
- Used for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. Commonly used for interacting with web APIs.
What is the purpose of the System.Threading
namespace?
- Provides types for multithreading and synchronization.
What is the purpose of the System.Threading.Tasks
namespace?
- Provides types for the Task-based Asynchronous Pattern (TAP), including
Task
,Task
,async
, andawait
.
What is the purpose of the Task Parallel Library (TPL)?
- The TPL is a set of public types and APIs in the
System.Threading.Tasks
andSystem.Threading.Tasks.Parallel
namespaces that simplify adding parallelism and concurrency to applications.
What is the difference between Parallel.For
and Parallel.ForEach
?
Parallel.For
: Executes afor
loop in parallel.Parallel.ForEach
: Executes aforeach
loop in parallel over a collection.
What is the purpose of the CancellationToken
? (Async/Multithreading)
CancellationToken
is used to signal cooperative cancellation of asynchronous or multithreaded operations. A source (CancellationTokenSource
) creates the token, and the code performing the operation checks the token'sIsCancellationRequested
property periodically and stops if cancellation is requested.
What is the difference between async void
and async Task
?
async Task
(orasync Task
): The preferred return type for async methods. Allows the caller to await the method, handle exceptions, and manage the task's state.async void
: Used primarily for event handlers. Cannot be awaited, and exceptions thrown from anasync void
method will crash the application (unless handled by a top-level exception handler). Avoid for general asynchronous methods.
What is the purpose of the ConfigureAwait(false)
method? (Async)
ConfigureAwait(false)
is used on an awaited task to prevent the continuation from being marshaled back to the original synchronization context (e.g., the UI thread). This can improve performance in library code and avoid deadlocks in certain scenarios, but it means the code afterawait
might run on a different thread.
What is the purpose of the using static
directive? (revisited)
- Allows you to use static members without specifying the class name.
What is the purpose of the nameof
operator? (revisited)
- Gets the string name of a variable, type, or member at compile time.
What is the purpose of the is
operator with type patterns? (revisited)
- Combines type checking and assignment.
What is the purpose of the switch
expression? (revisited)
- A concise way to return a value based on pattern matching.
What is the purpose of the using
declaration? (revisited)
- Ensures disposal of
IDisposable
objects at the end of the scope.
What is the purpose of the null-coalescing assignment
operator (??=
)? (revisited)
- Assigns if the left-hand operand is null.
What is the purpose of the Indices and Ranges
feature? (revisited)
- Provides convenient syntax for accessing sequence elements by index from the end and specifying ranges.
What is the purpose of the Target-typed new
expression? (revisited)
- Allows omitting the type name in
new
expressions when the type is clear from the context.
What are Records? (revisited)
- Immutable data carriers with value-based equality, concise syntax.
What is the purpose of the with
expression? (revisited)
- Creates a new instance of a record (or struct) with modifications.
What are Top-Level Statements? (revisited)
- Allows writing executable code directly in a file without a
Program
class andMain
method.
What are Global Using Directives? (revisited)
- Applies
using
directives to all files in a project.
What are File-Scoped Namespaces? (revisited)
- Declares a namespace that applies to the entire file without curly braces.
What is the purpose of the const
interpolated strings? (C# 10+)
- Allows using interpolated strings in
const
declarations, provided all interpolated values are also constants.
What is the purpose of Primary Constructors? (C# 12+)
- A concise way to declare constructor parameters directly in the class or struct header, which are then available throughout the class body.
What are Collection Expressions? (C# 12+)
- A concise syntax using square brackets (
[]
) to create common collection types like arrays, lists, and spans.
What is the purpose of the is not
pattern? (C# 9+)
- A negation pattern for the
is
operator, useful for checking if something is *not* of a certain type or *not* null.
What is the purpose of the or
, and
, and not
patterns? (C# 9+)
- Logical patterns that can be combined with other patterns for more complex matching.
What is the purpose of the
XML documentation tag?
- Used to inherit XML documentation comments from a base class, interface, or base member.
What is the purpose of the #nullable
directive? (C# 8+)
- Used to control the nullable context (enable or disable nullable reference types) within a specific part of the source code file.
What is the purpose of the required
keyword? (C# 11+)
- Applied to members (fields or properties) to indicate that they must be initialized by object initializers when an object is created.
What is the purpose of the scoped
keyword? (C# 11+)
- Applied to
ref
variables or method parameters to limit their lifetime to the current scope. This helps prevent dangling pointers/references.
What is the purpose of the file
access modifier? (C# 11+)
- Applied to types to indicate that they are only visible within the same source file.
What is the purpose of the raw string literals
? (C# 11+)
- A new way to declare string literals that can contain arbitrary text, including whitespace and special characters, without needing escape sequences. Defined using three or more double quotes (
"""
).
What is the purpose of the generic math
feature? (C# 11+)
- Allows defining generic types and methods that can work with different numeric types and perform mathematical operations on them using interfaces like
INumber
.
What is the difference between IEnumerable
and IEnumerator
?
IEnumerable
: Represents a collection that can be enumerated. It has a single method,GetEnumerator()
, which returns anIEnumerator
.IEnumerator
: Represents an object that can iterate over a sequence. It has methods likeMoveNext()
(moves to the next element),Current
(gets the current element), andReset()
(resets the enumerator).