Detailed answers to the 27 commonly asked .NET C# interview questions:
What are the four pillars of OOP? Explain each with examples.
Encapsulation: Bundling of data (fields) and methods (functions) that operate on the data within a single unit (class).
public class Employee {
private string name;
public string GetName() {
return name;
}
public void SetName(string newName) {
name = newName;
}
}
Inheritance: Mechanism where a class (derived class) inherits properties and behaviors from another class (base class).
public class Manager : Employee {
public void Manage() {
Console.WriteLine("Managing tasks...");
}
}
Polymorphism: Ability to present the same interface for different data types. Includes method overloading and method overriding.
public class Animal {
public virtual void MakeSound() {
Console.WriteLine("Animal sound");
}
}
public class Dog : Animal {
public override void MakeSound() {
Console.WriteLine("Bark");
}
}
Abstraction: Hiding complex implementation details and showing only the essential features of an object.
public abstract class Shape {
public abstract double Area();
}
public class Rectangle : Shape {
public override double Area() {
// Calculation logic
}
}
What is inheritance? How does C# support inheritance?
Inheritance: A mechanism where a class (derived or child class) inherits properties and behaviors from another class (base or parent class).
C# Support: C# supports single-class inheritance, meaning a derived class can inherit from only one base class. It enables code reusability and promotes the concept of "is-a" relationship.
public class Animal {
public void Eat() {
Console.WriteLine("Eating...");
}
}
public class Dog : Animal {
public void Bark() {
Console.WriteLine("Barking...");
}
}
What is polymorphism? Provide an example in C#.
Polymorphism: The ability of different objects to respond to the same message (method call) in different ways.
Example:
public class Animal {
public virtual void MakeSound() {
Console.WriteLine("Animal sound");
}
}
public class Dog : Animal {
public override void MakeSound() {
Console.WriteLine("Bark");
}
}
Animal myAnimal = new Dog();
myAnimal.MakeSound(); // Output: Bark
Explain the difference between var and dynamic keywords in C#.
var: Implicitly types the variable based on the assigned value at compile-time. It is statically typed.
var number = 10; // Compiler infers type as int
dynamic: Represents a type whose operations are resolved at runtime. It bypasses compile-time type checking.
dynamic obj = GetSomeObject();
obj.SomeDynamicMethod(); // Resolved at runtime
What is the difference between async and synchronous programming in C#?
Synchronous Programming: Executes tasks sequentially, blocking until each task completes before proceeding.
public void SyncMethod() {
// Perform synchronous operations
}
Asynchronous Programming: Allows tasks to run concurrently, freeing up the calling thread for other operations while waiting for asynchronous tasks to complete.
public async Task AsyncMethod() {
// Perform asynchronous operations
await SomeAsyncOperation();
}
What is the purpose of the using statement in C#?
using Statement: Ensures that IDisposable objects are properly disposed of after use, even if an exception occurs.
using (var fileStream = new FileStream("example.txt", FileMode.Open)) {
// Use fileStream
} // fileStream.Dispose() is called here automatically
What is exception handling in C#? Explain try, catch, and finally blocks.
Exception Handling: Mechanism to handle runtime errors (exceptions) gracefully, preventing application crashes.
try {
// Code that might throw an exception
throw new Exception("Something went wrong");
}
catch (Exception ex) {
// Handle the exception
Console.WriteLine($"Error: {ex.Message}");
}
finally {
// Optional block, executes regardless of whether an exception occurred
// Used for cleanup or resource releasing
}
What are custom exceptions? How do you create and use them in C#?
Custom Exceptions: User-defined exception classes that extend the base Exception class to handle specific error scenarios.
public class CustomException : Exception {
public CustomException(string message) : base(message) { }
}
try {
throw new CustomException("Custom error message");
}
catch (CustomException ex) {
Console.WriteLine($"Custom Exception: {ex.Message}");
}
LINQ: Language Integrated Query allows querying data from different data sources using a consistent syntax.
Benefits: Provides compile-time checking, type safety, and reduces the amount of code needed for querying data.
Example:
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var query = from num in numbers
where num % 2 == 0
select num;