C# Interview Questions


What is C#?

C# is a modern, object-oriented programming language developed by Microsoft as part of the .NET framework. It is widely used for developing various types of applications, including web, desktop, mobile, and enterprise software.

What are the key features of C#?

Some key features of C#:

  • Simple Syntax: Easy-to-understand syntax influenced by C and C++.
  • OOP Support: Full support for object-oriented programming principles.
  • Type Safety: Statically typed for compile-time type checking.
  • Memory Management: Automatic memory management via CLR.
  • Asynchronous Programming: Built-in async/await for responsive apps.
  • Exception Handling: Robust exception handling for error management.
  • LINQ: Language Integrated Query for data manipulation.
  • Cross-Platform: Increasingly cross-platform with .NET Core and .NET 5/6.
  • Interoperability: Support for integration with other languages/platforms.
  • Rich Standard Library: Extensive APIs for various development tasks.

What is the difference between value types and reference types in C#?

Some key differences between value types and reference types:

Aspect Value Types Reference Types
Storage Stored on the stack. Stored on the managed heap.
Memory Management Memory allocation is fixed and known. Memory allocation can vary.
Assignment Actual value is assigned. Reference to memory location is assigned.
Copying Copies actual data. Copies reference to the data.
Equality Comparison Compares actual data values. Compares memory addresses.

Explain the purpose of the 'async' and 'await' keywords in C#?

'async' is used to define methods that can be executed asynchronously, allowing other code to run while waiting for the asynchronous operation to complete. 'await' is used to indicate that the method should asynchronously wait for the completion of an asynchronous operation.

What is the purpose of the 'try', 'catch', and 'finally' blocks in C#?

The 'try' block is used to enclose code that may throw an exception. The 'catch' block is used to handle exceptions that are thrown within the 'try' block. The 'finally' block is used to specify code that should always be executed, regardless of whether an exception is thrown or not.

Explain the difference between 'out' and 'ref' keywords in C#.

Some key differences between 'out' and 'ref' keywords:

Aspect out Parameter Modifier ref Parameter Modifier
Initialization Does not require the variable to be initialized before being passed to the method. Requires the variable to be initialized before being passed to the method.
Passing Data Used for passing data from a method to the caller. Used for passing data bidirectionally between the caller and the method.
Method Modification Indicates that the method is expected to assign a value to the parameter. Indicates that the method can read and modify the parameter's value.
Requirement The method must assign a value to the out parameter before exiting. The method can read and modify the ref parameter's value, but it's not required to assign a value before exiting.
Usage Suitable for scenarios where the method needs to return multiple values. Suitable for scenarios where the method needs to modify the original value of a variable passed to it.

 Explain the purpose of the 'volatile' keyword in C#?

The 'volatile' keyword is used to indicate that a field may be modified by multiple threads that are executing at the same time. It ensures that all reads and writes to the field are performed directly on the main memory, rather than being cached by individual threads.

public class Example {
    private volatile bool flag = true;

    public void ToggleFlag() {
        flag = !flag;
    }
}

What are delegates in C#?

Delegates are type-safe function pointers that are used to pass methods as arguments to other methods or to define callback methods. They provide a way to encapsulate and pass around methods as if they were objects.

What is the difference between 'abstract' and 'interface' in C#?

Some key differences between 'abstract' and 'interface':

Aspect abstract Class interface
Definition Can contain both abstract and non-abstract methods, and may have fields, properties, constructors, and destructors. Contains only method and property signatures, without any implementation.
Inheritance Can provide partial implementation and be inherited by derived classes using the extends keyword. Can be implemented by classes using the implements keyword, allowing multiple interface implementations.
Multiple Inheritance Does not support multiple inheritance. Supports multiple inheritance, allowing a class to implement multiple interfaces.
Member Accessibility Can have various access modifiers for members, allowing different levels of visibility. All members are implicitly public and cannot contain any implementation.

What is the use of 'using' statement in C#?

The 'using' statement is used to ensure that IDisposable objects are properly disposed of when they are no longer needed. It automatically calls the Dispose method on the object when the block exits, even if an exception is thrown.

 What is the purpose of the 'sealed' modifier in C#?

The 'sealed' modifier is used to prevent a class from being inherited by other classes. It is often used to restrict inheritance and ensure that certain classes cannot be extended or modified. When applied to a method, it prevents the method from being overridden in derived classes.

public sealed class SealedClass {
    public void Method() {
        Console.WriteLine("Sealed class method.");
    }
}

What is the difference between 'override' and 'virtual' in C#?

Some key differences between'override' and 'virtual':

Aspect virtual override
Usage Used to indicate that a method, property, or indexer can be overridden in derived classes. Used to provide a new implementation for a method, property, or indexer that is marked as virtual in the base class.
Inheritance Can be inherited from a base class into derived classes, allowing them to override the implementation. Must override a method, property, or indexer that is marked as virtual in the base class to provide a new implementation.
Implementation Provides a default implementation that can be optionally overridden in derived classes. Overrides the implementation of a method, property, or indexer defined in the base class with a new implementation in the derived class.

What is the purpose of the 'static' keyword in C#?

The 'static' keyword is used to declare members (variables, methods, properties) that belong to the type itself rather than to instances of the type. Static members are shared among all instances of the class.

What is the difference between 'String' and 'StringBuilder' in C#?

Some key differences between 'String' and 'StringBuilder':

Aspect String StringBuilder
Mutability Immutable; once created, cannot be modified. Mutable; allows dynamic modification of its content.
Memory Allocation Creates a new instance in memory every time it's modified, potentially leading to memory fragmentation. Uses a resizable buffer to efficiently manage memory allocation, reducing overhead for frequent modifications.
Performance Less efficient for frequent modifications due to memory allocation overhead. More efficient for frequent modifications, especially in scenarios involving concatenation or large strings.
Usage Suitable for scenarios where the content doesn't change frequently. Suitable for scenarios where dynamic modification of string content is required, such as building strings dynamically or performing frequent concatenations.

Explain the concept of inheritance in C#.

Inheritance is a mechanism by which a class can inherit properties, methods, and other members from another class. The class that is being inherited from is called the base class or parent class, and the class that inherits from it is called the derived class or child class.

What are the different access modifiers in C#?

C# provides several access modifiers to control the visibility and accessibility of types and members. These include 'public', 'private', 'protected', 'internal', and 'protected internal'.

public class ExampleClass {
    public int publicVariable;
    private string privateVariable;
    protected internal float protectedInternalVariable;
    internal static double internalStaticVariable;
}

What is the difference between 'IEnumerable' and 'IQueryable' in LINQ?

Some key differences between 'IEnumerable' and 'IQueryable' in LINQ:

Aspect IEnumerable IQueryable
Definition Represents a forward-only cursor of a collection, allowing iteration over its elements. Represents a query that can be executed against a data source, supporting filtering, sorting, and projection.
Execution Executes queries on the client-side, meaning that all operations are performed in-memory after data retrieval from the data source. Executes queries on the server-side, allowing for deferred execution and the possibility of composing more efficient SQL queries.
Deferred Execution Does not support deferred execution, meaning that operations are performed immediately when invoked. Supports deferred execution, allowing query operations to be built up and executed later, potentially optimizing database access.
Suitable For Suitable for querying in-memory collections like arrays, lists, or collections retrieved from databases and other sources. Suitable for querying remote data sources like databases, where query composition and execution optimization are important.

Explain the concept of boxing and unboxing in C#?

Boxing is the process of converting a value type to a reference type, while unboxing is the process of converting a reference type back to a value type. This conversion involves copying the value from the stack to the heap (boxing) or from the heap to the stack (unboxing).

 What are attributes in C#?

Attributes provide a way to add metadata to types and their members. They can be used to provide additional information to the compiler, runtime, or other tools about how the code should be treated or processed.

unsafe class UnsafeExample {
    static void Main() {
        int x = 10;
        int* ptr = &x;
        Console.WriteLine("Value of x: " + *ptr);
    }
}

What is the purpose of the 'base' keyword in C#?

The 'base' keyword is used to access members of the base class from within a derived class. It can be used to call constructors, methods, and properties of the base class.

What is the difference between '== 'and 'Equals()' method in C#?

Some key differences between '== 'and 'Equals()' method:

Aspect == Operator Equals() Method
Usage Used to compare the equality of two objects. Used to check the equality of two objects by invoking the Equals() method.
Overloading Can be overloaded for custom types to define custom equality comparison logic. Can be overridden in classes to provide custom equality comparison logic.
Implementation Resolved at compile time based on the object's type and the available overload of the == operator. Resolved at runtime based on the type of the object on which it is called and the overridden implementation in the class.
Null Handling Handles null values gracefully, returning true if both operands are null, false if only one operand is null, and invoking the Equals() method if both operands are non-null. Requires additional null-checking logic to handle null values before invoking Equals() to avoid null reference exceptions.
Example csharp if (obj1 == obj2) { /* Code */ } csharp if (obj1.Equals(obj2)) { /* Code */ }

What are indexers in C#?

Indexers are a special type of property that allows instances of a class to be indexed as if they were arrays. They provide a way to access elements of a collection using array-like syntax.

What are lambda expressions in C#?

Lambda expressions are anonymous functions that can be used to create delegates or expression tree types. They provide a concise way to represent methods with a single line of code.

What is the difference between 'throw' and 'throw ex' in C#?

'throw' is used to re-throw the current exception without losing the original stack trace, while 'throw ex' is used to throw a new exception that wraps the original exception, potentially losing the original stack trace.

try {
    // Some code that may throw an exception
    throw new Exception("An error occurred.");
} catch (Exception ex) {
    // Log exception
    Console.WriteLine("Exception caught: " + ex.Message);
    // Rethrow exception
    throw; // preserves original stack trace

    // Alternatively
    // throw ex; // new stack trace starts from here
}

What is the difference between 'throw' and 'throw ex' in C# exceptions handling?

Some key differences between 'throw' and 'throw ex' exceptions handling:

Aspect throw throw ex
Preserving Stack Trace Preserves the original stack trace of the exception, providing more detailed information about where the exception occurred. Resets the stack trace, replacing it with the current method's stack trace, potentially losing valuable information about the original source of the exception.
Performance More efficient, as it doesn't incur the overhead of capturing and resetting the stack trace. May have a slight performance overhead due to capturing and resetting the stack trace.
Recommended Practice Generally recommended as it maintains the integrity of the exception's original context, aiding in debugging and troubleshooting. Generally discouraged due to the potential loss of valuable information contained in the original stack trace.
Example csharp throw new Exception("Error occurred"); csharp try { /* Some code */ } catch (Exception ex) { throw ex; }

What is the purpose of the 'using' directive in C#?

The 'using' directive is used to import namespaces, allowing you to reference types within those namespaces without having to fully qualify their names. It simplifies code and improves readability.

What is a constructor in C#?

A constructor is a special method that is automatically called when an instance of a class is created. It is used to initialize the object's state and perform any necessary setup.

public class Person {
    public string Name;
    public int Age;

    // Constructor
    public Person(string name, int age) {
        Name = name;
        Age = age;
    }
}

// Usage
Person person = new Person("John", 30);

What is method overloading in C#?

Method overloading is a feature that allows a class to have multiple methods with the same name but different signatures. This enables you to provide different implementations of a method for different parameter types or numbers.

What is method overriding in C#?

Method overriding is a feature of inheritance that allows a derived class to provide a specific implementation for a method that is already defined in its base class. It enables polymorphism and dynamic method resolution.

class Animal {
    public virtual void MakeSound() {
        Console.WriteLine("Animal makes a sound.");
    }
}

class Dog : Animal {
    public override void MakeSound() {
        Console.WriteLine("Dog barks.");
    }
}

// Usage
Animal animal = new Dog();
animal.MakeSound(); // Output: Dog barks.

What is the purpose of the 'params' keyword in C#?

The 'params' keyword allows you to specify a variable number of parameters for a method. It allows you to pass a variable number of arguments to the method, which are then treated as an array inside the method.

What is the difference between throw and throw new Exception() in C#?

Some key differences between throw and throw new Exception() in C#:

Aspect throw throw new Exception()
Usage Used to rethrow the current exception or to throw a new one without specifying its type. Used to throw a new instance of an exception with a specified type and optional message.
Exception Type Can only be used to rethrow the current exception, preserving its type and message. Allows you to create and throw a new instance of any exception type derived from Exception.
Message (Optional) Does not allow specifying a custom message. Allows specifying a custom error message for the thrown exception.
Example csharp throw; csharp throw new Exception("Custom message");

What is the purpose of the 'as' operator in C#?

The 'as' operator is used for explicit casting between compatible types. If the conversion is not possible, it returns null instead of throwing an exception, making it safer than traditional casting.

object obj = "Hello";
string str = obj as string;
if (str != null) {
    Console.WriteLine("Length of string: " + str.Length);
} else {
    Console.WriteLine("Object is not a string.");
}

What is the purpose of the 'is' operator in C#?

The 'is' operator is used to check whether an object is compatible with a given type. It returns true if the object can be cast to the specified type, and false otherwise.

What is the purpose of the 'readonly' keyword in C#?

The 'readonly' keyword is used to create immutable fields, meaning their values cannot be changed once they are assigned. They can only be initialized at the time of declaration or in the constructor.

public class ExampleClass {
    public const int ConstValue = 10;
    public readonly int ReadOnlyValue;

    public ExampleClass(int value) {
        ReadOnlyValue = value;
    }
}

What is the difference between readonly and const in C#?

Some key differences between readonly and const in C#:

Aspect readonly const
Initialization Can be initialized at the time of declaration or in the constructor. Must be initialized at the time of declaration.
Mutability Can be assigned a value multiple times, but only within the constructor or at the point of declaration. Cannot be reassigned a value after initialization.
Scope Can be used with fields, properties, or local variables. Can only be used with fields and local variables, not properties.
Usage Used for values that can be determined at runtime or when their value may change over time. Used for values that are known at compile-time and won't change during program execution.
Example csharp readonly int maxAttempts = 3; csharp const float PI = 3.14f;

What is a namespace in C#?

A namespace is a way to organize code into logical groups and prevent naming conflicts. It provides a hierarchical organization of classes, structs, interfaces, enums, and delegates.

What is the purpose of the 'checked' and 'unchecked' keywords in C#?

'checked' and 'unchecked' are used to control overflow checking for arithmetic operations. 'checked' enables overflow checking, causing an exception to be thrown if an arithmetic operation results in overflow. 'unchecked' disables overflow checking, allowing overflow to occur without throwing an exception.

What is the purpose of the 'using' statement in C#?

The 'using' statement is used to ensure that resources such as file streams, database connections, or network sockets are properly disposed of when they are no longer needed. It automatically calls the Dispose method on objects that implement the IDisposable interface when the block exits, even if an exception is thrown.

using (StreamWriter writer = new StreamWriter("example.txt")) {
    writer.WriteLine("This is an example.");
}

What is the purpose of the 'lock' statement in C#?

The 'lock' statement is used to synchronize access to a shared resource in a multi-threaded environment. It ensures that only one thread can execute a block of code at a time by acquiring a mutual exclusion lock.

What are extension methods in C#?

Extension methods allow you to add new methods to existing types without modifying their source code. They provide a way to extend the functionality of classes, structs, interfaces, or enums without inheritance, making it easier to work with third-party or framework types.

What are nullable types in C#?

Nullable types allow you to represent value types that can have a null value in addition to their normal range of values. They are useful when working with databases or other data sources that may contain null values.

int? nullableInt = null;
double? nullableDouble = 3.14;

if (nullableInt.HasValue) {
    Console.WriteLine("Nullable int: " + nullableInt.Value);
} else {
    Console.WriteLine("Nullable int is null.");
}

What is the purpose of the 'yield' keyword in C#?

The 'yield' keyword is used in iterator methods to return each element of a sequence one at a time. It allows you to create custom iterators without having to implement the entire IEnumerator interface manually.

What is the purpose of the 'ref' and 'out' keywords in C#?

'ref' and 'out' are used to pass arguments by reference instead of by value. 'ref' is used when the method needs to read and modify the value of the argument, while 'out' is used when the method needs to assign a new value to the argument.

public void ModifyValue(ref int x) {
    x += 10;
}

public void Initialize(out int y) {
    y = 20;
}

// Usage
int a = 5;
ModifyValue(ref a);
Console.WriteLine(a); // Output: 15

int b;
Initialize(out b);
Console.WriteLine(b); // Output: 20

What is the purpose of the 'params' keyword in C#?

The 'params' keyword allows you to specify a variable number of parameters for a method. It simplifies calling methods with a variable number of arguments by allowing you to pass them as an array.

What are anonymous types in C#?

Anonymous types allow you to create objects with properties defined at compile-time without having to explicitly declare a class. They are useful for temporary data structures or when working with LINQ queries that return projected results.

What is the purpose of the 'in' modifier in C#?

The 'in' modifier is used to indicate that an argument is passed by reference but cannot be modified by the called method. It is primarily used for performance optimization when passing large value types.

public void DisplayValues(in int x, in int y) {
    Console.WriteLine($"Values: {x}, {y}");
}

// Usage
int a = 10, b = 20;
DisplayValues(in a, in b); // Output: Values: 10, 20

What is the purpose of the 'out' modifier in C#?

The 'out' modifier is used to indicate that an argument is passed by reference and is intended to be assigned a value by the called method. It is commonly used for methods that return multiple values.

What is the purpose of the 'unsafe' keyword in C#?

The 'unsafe' keyword is used to mark a block of code as unsafe, allowing the use of pointers and other low-level constructs that are not normally allowed in managed code. It is typically used when working with interop or when performance optimizations require direct memory manipulation.

What is the difference between a value type and a reference type in C#?

Some key differences between a value type and a reference type:

Aspect Value Types Reference Types
Storage Stored directly on the stack Stored on the managed heap
Memory Allocation Memory allocation is fixed and known Memory allocation can vary
Assignment Assigns actual data Assigns a reference to data
Copying Copying duplicates the value Copying duplicates the reference
Equality Comparison Compares actual data values Compares memory addresses
Examples int, float, char, struct string, class, interface, delegate

What is garbage collection in C#?

Garbage collection is the process by which the .NET runtime automatically deallocates memory that is no longer in use by the program. It periodically scans the managed heap for objects that are no longer reachable and frees up the memory occupied by those objects. This helps prevent memory leaks and simplifies memory management for developers.

class MyClass {
    public int[] Array = new int[1000000];
}

// Usage
MyClass[] array = new MyClass[1000];
for (int i = 0; i < 1000; i++) {
    array[i] = new MyClass();
}
array = null; // Objects become eligible for garbage collection
GC.Collect(); // Garbage collection is triggered

What is the difference between a struct and a class in C#?

In C#, structs are value types, while classes are reference types. Structs are typically used for lightweight objects that have value semantics and are often passed by value, while classes are used for more complex objects that have reference semantics and are passed by reference. Additionally, structs cannot be inherited or used in polymorphic scenarios like classes can.