# Top 20 C# Interview Questions and Answers

Preparing for a C# interview can be challenging, especially when you want to stand out and demonstrate a strong grasp of the language's fundamentals and advanced features. This article compiles the top 20 most commonly asked C# interview questions and provides clear, concise answers to help you understand and articulate key concepts confidently. From object-oriented programming principles and SOLID design patterns to asynchronous programming and LINQ, this guide covers a comprehensive range of topics. Whether you're a beginner or looking to refresh your knowledge, these questions and answers will equip you with the insights needed to succeed in your next technical interview.

1. **What is the difference between value types and reference types in C#?**
    
    **Answer:**
    
    * **Value Types:**
        
        * Stored in the stack.
            
        * Contain the actual data.
            
        * Examples: `int`, `double`, `bool`, `struct`, `enum`.
            
        * When assigned to a new variable, a copy is made.
            
    * **Reference Types:**
        
        * Stored in the heap.
            
        * Contain a reference to the data.
            
        * Examples: `class`, `interface`, `delegate`, `object`, `string`.
            
        * When assigned to a new variable, the reference is copied, not the object itself.
            
    
    **Example:**
    
    ```csharp
    int a = 5;
    int b = a; // b is a copy of a
    
    Person person1 = new Person();
    Person person2 = person1; // person2 references the same object as person1
    ```
    
2. **Explain the concept of delegates in C#.**
    
    **Answer:**
    
    A delegate is a type that represents references to methods with a specific parameter list and return type. It's similar to a function pointer in C++ but type-safe. Delegates are used to pass methods as arguments to other methods.
    
    **Example:**
    
    ```csharp
    public delegate int MathOperation(int x, int y);
    
    public int Add(int a, int b) => a + b;
    
    MathOperation operation = Add;
    int result = operation(3, 4); // result is 7
    ```
    
3. **What are events in C#, and how are they related to delegates?**
    
    **Answer:**
    
    Events are a way for a class to notify other classes or objects when something happens. They are based on delegates and provide a layer of abstraction and safety.
    
    **Example:**
    
    ```csharp
    public class Publisher
    {
        public event EventHandler OnChange;
    
        public void RaiseEvent()
        {
            OnChange?.Invoke(this, EventArgs.Empty);
        }
    }
    
    public class Subscriber
    {
        public void Subscribe(Publisher publisher)
        {
            publisher.OnChange += HandleChange;
        }
    
        private void HandleChange(object sender, EventArgs e)
        {
            Console.WriteLine("Event received.");
        }
    }
    ```
    
4. **What is LINQ, and why is it useful?**
    
    **Answer:**
    
    LINQ (Language Integrated Query) is a set of features that adds query capabilities to .NET languages. It allows querying collections using a SQL-like syntax. LINQ provides:
    
    * Consistency across different data sources.
        
    * Strongly typed queries with IntelliSense support.
        
    * Improved readability and maintainability.
        
    
    **Example:**
    
    ```csharp
    var numbers = new List<int> { 1, 2, 3, 4, 5 };
    var evenNumbers = from num in numbers
                      where num % 2 == 0
                      select num;
    ```
    
5. **Explain** `async` and `await` keywords in C# and how asynchronous programming works.
    
    **Answer:**
    
    * `async` keyword: Marks a method as asynchronous, allowing it to use `await` to suspend execution until an awaited task completes.
        
    * `await` keyword: Pauses the execution of the async method until the awaited task is complete.
        
    
    Asynchronous programming allows applications to remain responsive by performing tasks without blocking the main thread.
    
    **Example:**
    
    ```csharp
    public async Task<string> FetchDataAsync()
    {
        HttpClient client = new HttpClient();
        string data = await client.GetStringAsync("https://api.example.com/data");
        return data;
    }
    ```
    
6. **What is garbage collection in C#, and how does it work?**
    
    **Answer:**
    
    Garbage Collection (GC) is an automatic memory management feature that reclaims memory occupied by objects that are no longer in use. The GC runs on a separate thread and identifies unreferenced objects to free up memory, reducing memory leaks and fragmentation.
    
7. **What are extension methods, and how do you define them?**
    
    **Answer:**
    
    Extension methods allow adding new methods to existing types without modifying the original type or creating a new derived type. They are defined as static methods in a static class, with the `this` keyword preceding the first parameter.
    
    **Example:**
    
    ```csharp
    public static class StringExtensions
    {
        public static bool IsCapitalized(this string str)
        {
            if (string.IsNullOrEmpty(str)) return false;
            return char.IsUpper(str[0]);
        }
    }
    
    string word = "Hello";
    bool isCapitalized = word.IsCapitalized(); // Returns true
    ```
    
8. **What is the difference between** `const` and `readonly` in C#?
    
    **Answer:**
    
    * `const`:
        
        * Value is set at compile time and cannot be changed.
            
        * Implicitly static.
            
        * Only primitive types and strings can be `const`.
            
    * `readonly`:
        
        * Value can be set at runtime, typically in the constructor.
            
        * Can be instance-level or static.
            
        * Can be any type.
            
    
    **Example:**
    
    ```csharp
    public class MyClass
    {
        public const int ConstValue = 10;
        public readonly int ReadOnlyValue;
    
        public MyClass(int value)
        {
            ReadOnlyValue = value;
        }
    }
    ```
    
9. **Explain boxing and unboxing in C#.**
    
    **Answer:**
    
    * **Boxing:** The process of converting a value type to a reference type (object). The value is wrapped inside an object and stored on the heap.
        
    * **Unboxing:** The reverse process of extracting the value type from the object.
        
    
    **Example:**
    
    ```csharp
    int number = 42;
    object obj = number; // Boxing
    int unboxedNumber = (int)obj; // Unboxing
    ```
    
10. **What is the difference between** `abstract` classes and `sealed` classes in C#?
    
    **Answer:**
    
    * `abstract` class:
        
        * Cannot be instantiated.
            
        * May contain abstract methods without implementation.
            
        * Intended to be a base class.
            
    * `sealed` class:
        
        * Cannot be inherited.
            
        * Prevents other classes from deriving from it.
            
        * Useful for security and optimization.
            
11. **Explain what generics are and their benefits.**
    
    **Answer:**
    
    Generics allow the creation of classes, methods, and structures with placeholders for the type of data they store or use. Benefits include:
    
    * **Type Safety:** Errors are caught at compile time.
        
    * **Performance:** Eliminates the need for boxing/unboxing.
        
    * **Code Reusability:** Write code that works with any data type.
        
    
    **Example:**
    
    ```csharp
    public class GenericList<T>
    {
        private T[] items;
        // Implementation details
    }
    
    GenericList<int> intList = new GenericList<int>();
    ```
    
12. **What is the purpose of the** `dynamic` keyword in C#?
    
    **Answer:**
    
    The `dynamic` keyword tells the compiler to bypass compile-time type checking for a variable. Instead, the type is resolved at runtime. This is useful when interacting with dynamic languages, COM objects, or reflection.
    
    **Example:**
    
    ```csharp
    dynamic obj = GetDynamicObject();
    obj.SomeMethod(); // Compiler does not check if SomeMethod exists
    ```
    
13. **What is the difference between** `IEnumerable` and `IQueryable`?
    
    **Answer:**
    
    * `IEnumerable`:
        
        * Namespace: `System.Collections`
            
        * Executes queries in-memory.
            
        * Suitable for querying in-memory collections like lists and arrays.
            
        * LINQ to Objects.
            
    * `IQueryable`:
        
        * Namespace: `System.Linq`
            
        * Allows for remote query execution, like in a database.
            
        * Suitable for querying external data sources.
            
        * LINQ to SQL, LINQ to Entities.
            
14. **Explain the purpose of** `partial` classes and methods.
    
    **Answer:**
    
    * **Partial Classes:**
        
        * Allow a class to be split across multiple files.
            
        * Useful for separating auto-generated code from developer-written code.
            
        * All parts must use the `partial` keyword and be in the same namespace.
            
    * **Partial Methods:**
        
        * Declared within partial classes.
            
        * Allow method declarations without implementation.
            
        * If no implementation is provided, the method and its calls are removed at compile time.
            
    
    **Example:**
    
    ```csharp
    // File1.cs
    public partial class SampleClass
    {
        partial void OnSomethingHappened();
    }
    
    // File2.cs
    public partial class SampleClass
    {
        partial void OnSomethingHappened()
        {
            // Method implementation
        }
    }
    ```
    
15. **What are anonymous types in C#?**
    
    **Answer:**
    
    Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without explicitly defining a type.
    
    **Example:**
    
    ```csharp
    var person = new { Name = "Alice", Age = 30 };
    Console.WriteLine(person.Name); // Outputs: Alice
    ```
    
    * Properties are inferred from the assigned values.
        
    * The type is created by the compiler and is anonymous.
        
16. **What is the difference between** `throw` and `throw ex` in exception handling?
    
    **Answer:**
    
    * `throw`:
        
        * Rethrows the current exception while preserving the original stack trace.
            
        * Preferred method for rethrowing exceptions.
            
    * `throw ex`:
        
        * Creates a new exception object.
            
        * Resets the stack trace, making it harder to trace the origin of the exception.
            
    
    **Example:**
    
    ```csharp
    try
    {
        // Some code
    }
    catch (Exception ex)
    {
        // Log exception
        throw; // Preserves stack trace
    }
    ```
    
17. **What is the purpose of the** `yield` keyword in C#?
    
    **Answer:**
    
    The `yield` keyword simplifies the implementation of iterator methods. It allows methods to return elements one at a time without the need to create an intermediate collection.
    
    **Example:**
    
    ```csharp
    public IEnumerable<int> GenerateNumbers()
    {
        for (int i = 0; i < 5; i++)
        {
            yield return i;
        }
    }
    
    foreach (var num in GenerateNumbers())
    {
        Console.WriteLine(num);
    }
    ```
    
18. **Explain the concept of nullable types and how to use them.**
    
    **Answer:**
    
    Nullable types allow value types to represent `null` values. They are declared using the `?` suffix.
    
    **Example:**
    
    ```csharp
    int? nullableInt = null;
    if (nullableInt.HasValue)
    {
        Console.WriteLine(nullableInt.Value);
    }
    else
    {
        Console.WriteLine("Value is null");
    }
    ```
    
    * `HasValue`: Indicates whether the variable contains a value.
        
    * `Value`: Gets the value if `HasValue` is true.
        
19. **What are** `async` lambdas, and how are they used?
    
    **Answer:**
    
    `async` lambdas are anonymous functions that are marked with the `async` keyword, allowing the use of `await` within them. They are useful in asynchronous programming, especially with event handlers and delegates.
    
    **Example:**
    
    ```csharp
    // Async lambda assigned to a delegate
    Func<Task> asyncOperation = async () =>
    {
        await Task.Delay(1000);
        Console.WriteLine("Operation completed");
    };
    
    await asyncOperation();
    ```
    
20. **What is a** `Task` in C#, and how is it different from a `Thread`?
    
    **Answer:**
    
    * `Task`:
        
        * Represents an asynchronous operation.
            
        * Managed by the Task Parallel Library (TPL).
            
        * Uses the thread pool for efficient resource utilization.
            
        * Supports continuations and can return results.
            
    * `Thread`:
        
        * Represents a separate path of execution.
            
        * More resource-intensive.
            
        * Managed directly by the operating system.
            
        * Less flexible for asynchronous programming.
            
    
    **Example:**
    
    ```csharp
    // Using Task
    Task.Run(() => DoWork());
    
    // Using Thread
    Thread thread = new Thread(new ThreadStart(DoWork));
    thread.Start();
    ```
    
    * **Tasks** are preferred in modern asynchronous programming due to their simplicity and efficiency.
        

---

These questions cover a range of essential topics in C#, from basic concepts to advanced features. Reviewing them will help solidify your understanding and prepare you for common questions in a C# interview. Make sure to understand not just the answers but also the underlying concepts, as interviewers may ask follow-up questions or require you to provide examples.
