C# Interview Questions

Here are the top 50 commonly asked questions in C# interviews. Whether you’re just starting your preparation or need a quick refresher, these questions and answers will help you tackle your interview with confidence.

Basic C# Interview Questions with Answers

1. What is C#?

C# is a modern, high-level programming language developed by Microsoft. It is designed for building a wide range of applications that run on the .NET Framework.

2. What are the features of C#?

C# features include strong typing, component-oriented programming, automatic memory management (garbage collection), and support for structured exception handling.

3. Explain the difference between value types and reference types in C#.

Value types store their data directly in memory, while reference types store a reference to the data’s memory location. Examples of value types include integers and characters, while examples of reference types include classes and interfaces.

4. What is the difference between “const” and “readonly” in C#?

const” is a compile-time constant, while “readonly” can be assigned a value at runtime but cannot be modified thereafter. “const” is static by default, while “readonly” can be instance-level.

5. What is boxing and unboxing in C#?

Boxing is the process of converting a value type to a reference type, and unboxing is the reverse process. It allows value types to be treated as objects.

6. What is the purpose of using “using” statement in C#?

The “using” statement is used to define a scope in which resources are automatically disposed of when they are no longer needed. It is commonly used with objects that implement the IDisposable interface, such as file streams and database connections.

advertisement
advertisement

7. What is the difference between “==” and “.Equals()” in C#?

“==” is used to compare the reference identity of two objects, whereas “.Equals()” is used to compare the contents or values of two objects.

8. Explain the difference between an interface and an abstract class in C#.

An interface only provides method signatures, while an abstract class can contain method implementations. A class can implement multiple interfaces, but it can inherit only one abstract class.

9. What are delegates in C#?

Delegates are type-safe function pointers that allow methods to be passed as parameters to other methods. They are used to implement callbacks and event handling in C#.

10. What is a lambda expression in C#?

A lambda expression is an anonymous function that can be used to create delegates or expression tree types. It provides a concise way to write inline functions.

11. What is the difference between “IEnumerable” and “IQueryable” in C#?

IEnumerable” is used to represent a forward-only cursor for iterating over a collection, while “IQueryable” is used to represent a query that can be executed against a data source.

12. Explain the “using” directive in C#.

The “using” directive is used to import namespaces in C#, allowing access to types and members defined in those namespaces without fully qualifying their names.

13. What is the purpose of the “async” and “await” keywords in C#?

The “async” keyword is used to define asynchronous methods, and the “await” keyword is used to asynchronously wait for the completion of asynchronous operations without blocking the thread.

14. What is the purpose of the “try”, “catch”, and “finally” blocks in C#?

The “try” block is used to enclose code that may throw exceptions, the “catch” block is used to handle exceptions, and the “finally” block is used to specify code that will always execute, regardless of whether an exception occurs.

15. What is the difference between “ref” and “out” parameters in C#?

Both “ref” and “out” parameters are used to pass arguments by reference, but “ref” parameters must be initialized before being passed to the method, while “out” parameters can be assigned a value inside the method.

advertisement

16. Explain the concept of inheritance in C# with an example.

Inheritance allows a class to inherit properties and behavior from another class. For example, a “Vehicle” class can have properties like “Make” and “Model,” and a “Car” class can inherit from the “Vehicle” class and add its own properties like “NumberOfDoors” and “Color.”

17. What is method overloading in C#?

Method overloading allows multiple methods in the same class to have the same name but different parameter lists. This allows for more flexible and readable code.

18. What is method overriding in C#?

Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This allows for polymorphic behavior.

19. Explain the concept of encapsulation in C# with an example.

Encapsulation is the bundling of data and methods that operate on the data into a single unit. For example, a “Car” class might encapsulate properties like “Speed” and “FuelLevel,” along with methods like “Accelerate” and “Refuel.”

20. What is a namespace in C#?

A namespace is a way to organize code into logical groups. It helps avoid naming conflicts and provides a way to access types and members in a hierarchical manner.

advertisement

Intermediate C# Interview Questions with Answers

21. What is the difference between “StringBuilder” and “String” in C#?

String” objects are immutable, meaning they cannot be changed after they are created, while “StringBuilder” objects are mutable and allow for efficient manipulation of strings.

22. Explain the concept of polymorphism in C# with an example.

Polymorphism allows objects of different types to be treated as objects of a common superclass. For example, a “Shape” superclass might have a “Draw” method, and subclasses like “Circle” and “Rectangle” can override this method to provide their own implementation.

23. What is the purpose of the “yield” keyword in C#?

The “yield” keyword is used in iterator methods to return a sequence of values one at a time. It allows for the deferred execution of sequences, improving performance and memory usage.

24. What is a nullable type in C#?

A nullable type allows a value type to represent a range of values, including null. It is declared by appending a “?” to the underlying value type, such as “int?”.

25. Explain the difference between “struct” and “class” in C#?

struct” is a value type, while “class” is a reference type. Structs are typically used for lightweight objects that have value semantics, while classes are used for more complex objects with reference semantics.

26. What are access modifiers in C#?

Access modifiers specify the accessibility of types and members in C#. They include “public”, “private”, “protected”, “internal”, and “protected internal”.

27. What is the purpose of the “sealed” keyword in C#?

The “sealed” keyword is used to prevent a class from being inherited. It is often used to create immutable classes or to prevent further specialization of a class.

28. What is the purpose of the “volatile” keyword in C#?

The “volatile” keyword indicates that a field may be modified by multiple threads that are executing at the same time. It prevents the compiler from optimizing away memory accesses to that field.

29. Explain the concept of event handling in C# with an example.

Event handling allows objects to subscribe to and receive notifications about events that occur in other objects. For example, a button control might raise a “Click” event, and other objects can subscribe to this event to perform specific actions when the button is clicked.

30. What is a class in C#?

A class is a fundamental building block of object-oriented programming in C#. It encapsulates data for the object and methods to manipulate that data. Classes provide a blueprint for creating objects, defining their properties, methods, and behaviors.

31. What are indexers in C#?

Indexers in C# allow objects to be indexed like arrays, enabling access to elements using square brackets [] notation. They provide a way to define custom collection-like behavior for classes, allowing instances of the class to be accessed using an index.

32. How do you use StreamWriter and StreamReader classes in C#?

StreamWriter and StreamReader are classes in the System.IO namespace that provide functionality for writing to and reading from files, respectively. StreamWriter is used to write text data to a file, while StreamReader is used to read text data from a file.

33. What are stream classes in C#?

Stream classes in C# are part of the System.IO namespace and provide a uniform interface for reading from and writing to different data sources, such as files, memory, network sockets, and more. They abstract away the underlying details of I/O operations, making it easier to work with various data sources in a consistent manner.

34. What are multicast delegates in C#?

Multicast delegates in C# allow a single delegate instance to refer to and invoke multiple methods. When a multicast delegate is invoked, it sequentially calls each method in its invocation list. Multicast delegates are commonly used in event handling scenarios where multiple event handlers need to be notified when an event occurs.

35. What is the purpose of LINQ in C#?

LINQ (Language Integrated Query) in C# provides a powerful and expressive syntax for querying and manipulating data from different data sources, such as collections, arrays, XML, databases, and more. It allows developers to write queries directly within C# code, enabling easier data manipulation, filtering, sorting, grouping, and aggregation operations. LINQ enhances code readability and maintainability by providing a unified query syntax across different data sources.

36. What is a static class in C#?

A static class in C# is a class that cannot be instantiated and can only contain static members. It is often used to group related utility methods together.

37. How do you implement IDisposable interface in C#?

The IDisposable interface is used to release unmanaged resources held by an object. To implement IDisposable, you need to define a Dispose method that releases the resources and optionally implement a finalizer to release resources if Dispose was not called explicitly. The Dispose method should also be called from the object’s finalizer to ensure proper cleanup.

38. How do you handle null reference exceptions in C#?

Null reference exceptions occur when you try to access members of a null object reference. To handle them, you can use conditional null checking with the “?” operator or use the null conditional operator “?.” introduced in C# 6.0.

39. How do you implement a singleton pattern in C#?

There are multiple ways to implement the singleton pattern in C#, but one common approach is to make the class constructor private, create a static field to hold the single instance of the class, and provide a static method to access that instance.

40. What are anonymous types in C#?

Anonymous types allow you to create objects without explicitly defining a class or structure. They are useful for storing temporary data or when you need to return multiple values from a method. Anonymous types are defined using the “new { }” syntax and are often used in LINQ queries.

C# Programming Interview Questions with Answers

41. What will be the output of the following C# program?

using System;
 
class Program
{
    static void Main(string[] args)
    {
        int x = 5;
        int y = x++;
        Console.WriteLine(y);
    }
}

Answer: 5

Explanation: In this C# program, the variable x is initialized with the value 5. Subsequently, y is assigned the value of x using the post-increment operator x++. Post-increment first assigns the current value of x to y and then increments x by 1. Consequently, y retains the value 5. Finally, the program prints the value of y to the console. Thus, the output of the program is 5.

42. What will be the output of the following C# program?

using System;
 
class Program
{
    static void Main(string[] args)
    {
        int result = 1 + 2 * 3 / 2 - 4;
        Console.WriteLine(result);  // Output: 1
    }
}

Answer: 0

Explanation:

  • The expression 1 + 2 * 3 / 2 – 4 is evaluated based on operator precedence.
  • Multiplication and division have higher precedence than addition and subtraction.
  • So, 2 * 3 is evaluated first, resulting in 6.
  • Then, 6 / 2 is evaluated, resulting in 3.
  • Finally, the expression becomes 1 + 3 – 4, which equals 0.
  • Therefore, the value of result is 0, which is printed to the console.

43. What will be the output of the following C# program?

using System;
 
class Program
{
    static void Main(string[] args)
    {
        int? x = null;
        int y = x ?? 2;
        Console.WriteLine(y);
    }
}

Answer: 2

Explanation:

  • In the statement int y = x ?? 2;, the null-coalescing operator ?? checks if the nullable integer x has a value.
  • Since x is null, the operator returns the right-hand operand, which is 2.
  • Therefore, y is assigned the value 2, which is then printed to the console.

44. What will be the output of the following C# program?

using System;
 
class Program
{
    static void Main(string[] args)
    {
        int x = 8;
        int y = ++x;
        Console.WriteLine($"x: {x}, y: {y}");
    }
}

Answer: x: 9, y: 9

Explanation: In this C# program, the variable x is initialized with the value 8. Then, the pre-increment operator ++x is used to increment the value of x by 1 before assigning it to the variable y. As a result, both x and y end up with the value 9. Finally, the values of x and y are printed to the console using string interpolation. Thus, the output of the program is x: 9, y: 9.

45. What will be the output of the following C# program?

using System;
 
class Program
{
    static void Main(string[] args)
    {
        double a = 0.1 + 0.2;
        double b = 0.3;
        bool isEqual = Math.Abs(a - b) < double.Epsilon;
        Console.WriteLine(isEqual);
    }
}

Answer: True

Explanation: This C# program calculates the sum of 0.1 and 0.2, then compares it to 0.3. Due to floating-point precision, direct comparison may not yield expected results. Instead, it compares the absolute difference between the two values to the smallest positive double value (double.Epsilon). Since the difference is negligible, the program outputs “True”, indicating the two values are considered equal.

46. What will be the output of the following C# program?

using System;
 
int a = 5;
int b = a;
b = 10;
Console.WriteLine(a);

Answer: 5

Explanation: This C# program initializes variable a with the value 5, then assigns a to b. Even though b is later changed to 10, it doesn’t affect the value of a. Therefore, when a is printed, it remains 5.

47. What will be the output of the following C# program?

using System;
 
class Program
{
    static void Main(string[] args)
    {
        object obj = "123";
        int num = int.Parse(obj.ToString());
        Console.WriteLine(num);
    }
}

Answer: 123

Explanation: In this C# program, the variable obj is initially assigned the string “123”. The int.Parse method is then used to convert this string representation into an integer. Since the string “123” represents a valid integer, the parsed integer value 123 is stored in the variable num. Finally, the value of num is printed to the console, resulting in the output 123.

48. What will be the output of the following C# program?

using System;
 
class Program
{
    static void Main(string[] args)
    {
        int result = 10 + 5 * 2;
        Console.WriteLine(result);
    }
}

Answer: 20

Explanation:

  • In C#, multiplication has a higher precedence than addition.
  • So, 5 * 2 is evaluated first, resulting in 10.
  • Then, 10 is added to 10, resulting in 20.
  • Finally, the value of result (20) is printed to the console.

49. What will be the output of the following C# program?

using System;
 
class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 1, 2, 3 };
        Console.WriteLine(numbers[3]);
    }
}

Answer: IndexOutOfRangeException

Explanation:

  • The array numbers has indices 0, 1, and 2, containing elements {1, 2, 3}respectively.
  • the line Console.WriteLine(numbers[3]);, the program tries to access the element at index 3, which is beyond the bounds of the array.
  • Therefore, the program throws an IndexOutOfRangeException at runtime because there is no element at index 3 in the array numbers.

50. What will be the output of the following C# program?

using System;
 
public delegate int Operation(int x, int y);
 
class Program
{
    static void Main(string[] args)
    {
        Operation op = (a, b) => a * b;
        int result = op(4, 3);
        Console.WriteLine($"Result: {result}");
    }
}

Answer: 12

Explanation: The program defines a delegate Operation representing a method taking two integers and returning an integer. It assigns a lambda expression to the delegate op, performing multiplication. Invoking op(4, 3) computes 4 * 3, resulting in 12, which is printed as the output.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.