Top Interview Questions
C# (pronounced C-Sharp) is a modern, object-oriented programming language developed by Microsoft as part of its .NET framework. Designed to be simple, powerful, and versatile, C# enables developers to create a wide variety of applications, including desktop software, web applications, mobile apps, cloud services, and games.
C# combines the robustness of C++ with the simplicity of Visual Basic, offering strong type safety, garbage collection, and automatic memory management. It has become a preferred language for enterprise-level software development due to its efficiency, scalability, and integration with Microsoft technologies.
C# was developed in the late 1990s under the leadership of Anders Hejlsberg, a renowned software architect known for his work on Turbo Pascal and Delphi. Microsoft aimed to create a language that could leverage the .NET framework to enable cross-platform, high-performance applications.
Key milestones in C# history include:
2000: C# 1.0 was officially released with Visual Studio .NET, introducing basic OOP concepts and .NET integration.
2005: C# 2.0 introduced generics, partial classes, nullable types, and iterators.
2007: C# 3.0 brought LINQ (Language Integrated Query), lambda expressions, and anonymous types, revolutionizing data manipulation.
2010-2012: C# 4.0 and 5.0 introduced dynamic typing, named arguments, asynchronous programming, and improved interoperability.
2015-Present: C# 6.0, 7.x, 8.0, 9.0, and 10.0 introduced pattern matching, record types, top-level statements, nullable reference types, and advanced asynchronous features.
C# continues to evolve, particularly with .NET 5/6/7, making it suitable for cross-platform development on Windows, macOS, Linux, and mobile platforms via Xamarin.
C# is a high-level, multi-paradigm language designed for modern software development. Its main features include:
Object-Oriented Programming (OOP): Supports encapsulation, inheritance, polymorphism, and abstraction.
Type Safety: Strongly typed language that minimizes runtime errors.
Automatic Memory Management: Uses garbage collection to manage memory automatically.
Interoperability: Can interact with unmanaged code, COM objects, and native Windows APIs.
Cross-Platform Development: With .NET Core and .NET 5/6/7, C# applications can run on multiple platforms.
Asynchronous Programming: Supports async/await to handle I/O-bound tasks efficiently.
Rich Standard Library: Provides extensive libraries for file handling, networking, database access, and graphics.
LINQ Support: Language-Integrated Query allows querying collections and databases directly using C# syntax.
Component-Oriented Programming: Facilitates the development of reusable software components.
Modern Language Constructs: Features like tuples, nullable types, pattern matching, and records improve readability and maintainability.
C# programs typically follow a class-based structure. Here’s a simple example:
using System;
namespace HelloWorldApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
Key elements:
Namespace: Organizes code logically (namespace HelloWorldApp).
Class: Defines a blueprint for objects (class Program).
Main Method: Entry point of the application (static void Main).
Console.WriteLine: Prints output to the console.
C# syntax is similar to C++ and Java, making it easier for developers familiar with those languages to learn.
C# supports multiple programming paradigms, making it versatile:
Object-Oriented Programming (OOP): Classes and objects model real-world entities.
Procedural Programming: Methods and functions support step-by-step instruction execution.
Functional Programming: Lambda expressions, delegates, and LINQ enable functional patterns.
Asynchronous Programming: Async and await keywords allow non-blocking operations.
Generic Programming: Generics allow classes and methods to operate on different data types safely.
This multi-paradigm support makes C# adaptable for various software architectures.
Class: Blueprint for creating objects.
Object: Instance of a class with attributes and behaviors.
Example:
class Car
{
public string Model { get; set; }
public void Start() => Console.WriteLine("Car started!");
}
Car myCar = new Car();
myCar.Model = "Tesla";
myCar.Start();
C# supports single inheritance and allows interfaces for multiple inheritance-like behavior.
class Vehicle
{
public void Start() => Console.WriteLine("Vehicle started");
}
class Bike : Vehicle
{
public void RingBell() => Console.WriteLine("Ring Ring!");
}
Polymorphism allows methods to have multiple forms:
Compile-Time (Method Overloading): Same method name, different parameters.
Run-Time (Method Overriding): Derived class provides specific implementation.
Encapsulation protects class data using access modifiers like private, protected, and public.
class BankAccount
{
private double balance;
public void Deposit(double amount) => balance += amount;
}
Abstraction hides internal implementation using abstract classes and interfaces:
abstract class Shape
{
public abstract double Area();
}
class Circle : Shape
{
public double Radius { get; set; }
public override double Area() => Math.PI * Radius * Radius;
}
Delegates: Type-safe pointers to methods.
Events: Enable event-driven programming, widely used in GUI apps.
LINQ allows querying collections elegantly:
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
C# is widely used across industries due to its robustness, scalability, and integration with .NET:
Web Development: ASP.NET Core for building dynamic web applications and APIs.
Desktop Applications: Windows Forms and WPF for GUI-based software.
Mobile Development: Xamarin allows cross-platform mobile apps using C#.
Game Development: Unity engine uses C# for scripting and game logic.
Cloud Computing: Azure development uses C# for cloud services and serverless functions.
Enterprise Applications: Banking, ERP, and CRM systems rely heavily on C# and .NET.
IoT Applications: Embedded devices and smart home systems use C# for connectivity and control.
Simple and Modern: Easy-to-learn syntax with modern programming features.
Object-Oriented: Encourages code reuse and modularity.
Type-Safe: Minimizes runtime errors.
Cross-Platform: Compatible with Windows, Linux, macOS, and mobile.
Integrated with .NET: Access to libraries, tools, and frameworks.
Robust Security: Supports strong typing, garbage collection, and code verification.
Active Community: Large developer ecosystem with extensive documentation.
Windows-Centric History: Although now cross-platform, it originally focused on Windows.
Memory Management Overhead: Garbage collection may introduce minor delays.
Less Control Over Hardware: Compared to C or C++, lower-level control is limited.
Learning Curve: Advanced features like async, delegates, and LINQ can be challenging for beginners.
C# continues to evolve with .NET:
.NET 7 and Beyond: Cross-platform, high-performance runtime for cloud, mobile, and desktop.
AI and Machine Learning: ML.NET allows AI solutions using C#.
Blazor: Build interactive web apps using C# instead of JavaScript.
Cloud-Native Development: Integration with Azure for microservices and serverless computing.
Modern Language Features: Records, pattern matching, nullable reference types, and asynchronous streams make C# increasingly developer-friendly.
C# is a powerful, versatile, and modern programming language that combines simplicity, performance, and flexibility. Its object-oriented nature, type safety, and .NET integration make it suitable for developing a wide range of applications—from web and mobile apps to enterprise systems and games.
With continuous updates, cross-platform support, and modern features like LINQ, async/await, and cloud integration, C# remains a future-proof choice for developers seeking a robust and scalable programming language.
Q1. What is C#?
Answer:
"C# is a modern, object-oriented, type-safe programming language developed by Microsoft as part of the .NET framework. It is used to build Windows applications, web applications, APIs, and more."
Q2. What are the main features of C#?
Object-Oriented Programming support
Type-safety and memory management via garbage collection
Rich class libraries in .NET framework
Support for exception handling
LINQ for querying data
Interoperability with COM and other languages
Q3. Difference between C# and Java
| Feature | C# | Java |
|---|---|---|
| Platform | Windows/.NET (cross-platform via .NET Core) | JVM (cross-platform) |
| Value Types | Supported | All objects |
| Properties/Events | Supported | Not natively supported |
| Delegates | Supported | No (use interfaces/callbacks) |
Q4. What is the .NET Framework?
"A software framework developed by Microsoft that provides a runtime (CLR), class libraries (BCL), and tools to build and run applications."
Q5. What is the Common Language Runtime (CLR)?
"CLR is the execution engine for .NET programs. It provides memory management, security, type safety, exception handling, and garbage collection."
Q6. What is CTS (Common Type System)?
"CTS defines how data types are declared, used, and managed in the .NET environment. It ensures interoperability between different .NET languages."
Q7. What is CLS (Common Language Specification)?
"CLS is a set of rules that .NET languages must follow to ensure interoperability between languages."
Q8. What are value types and reference types?
| Type | Description | Example |
|---|---|---|
| Value type | Stores data directly, allocated on stack | int, float, struct |
| Reference type | Stores address, allocated on heap | class, string, array |
Q9. Difference between string and StringBuilder
string: Immutable, slower for frequent changes
StringBuilder: Mutable, faster for multiple modifications
Q10. Difference between const and readonly
| Feature | const | readonly |
|---|---|---|
| Assignment | At compile-time | At runtime (in constructor) |
| Immutability | Always constant | Immutable after assignment |
| Scope | Class-level or method-level | Class-level |
Q11. What are nullable types in C#?
"Nullable types allow value types to store null in addition to their normal range. Declared using int? or Nullable<int>."
Q12. Difference between var and dynamic
var: Compiler infers type at compile-time; type is fixed
dynamic: Type is resolved at runtime; flexible but less safe
Q13. What is a class and object?
Class: Blueprint for creating objects
Object: Instance of a class
Q14. What is encapsulation?
"Encapsulation is wrapping data (fields) and methods inside a class and controlling access via access modifiers (private, public, protected)."
Q15. What is inheritance in C#?
"Inheritance allows a class to derive members from another class using : syntax. Supports single inheritance for classes and multiple inheritance via interfaces."
Q16. What is polymorphism?
"Polymorphism allows objects to behave differently based on context. Two types:
Compile-time: Method overloading, operator overloading
Run-time: Method overriding with virtual and override keywords"*
Q17. Difference between abstract class and interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Implementation | Can have implemented methods | Only method signatures (C# 8+ allows default) |
| Inheritance | Single inheritance | Multiple inheritance |
| Constructor | Allowed | Not allowed |
Q18. What are sealed and static classes?
sealed: Cannot be inherited
static: Cannot be instantiated; contains only static members
Q19. Difference between override and new in C#
override: Overrides a base class virtual method
new: Hides the base class method without overriding
Q20. What is an indexer in C#?
"Indexers allow objects to be indexed like arrays using this keyword."
Example:
class Sample {
private int[] data = new int[10];
public int this[int index] {
get { return data[index]; }
set { data[index] = value; }
}
}
Q21. What is garbage collection in C#?
"Garbage collector automatically frees memory occupied by objects that are no longer in use, reducing memory leaks."
Q22. What is IDisposable and using?
"IDisposable is an interface to release unmanaged resources manually. using ensures disposal automatically."
Example:
using(StreamReader sr = new StreamReader("file.txt")) {
// use sr
} // sr disposed automatically
Q23. Difference between stack and heap memory
| Feature | Stack | Heap |
|---|---|---|
| Allocation | Automatic | Dynamic via new |
| Lifetime | Method scope | Managed by GC |
| Size | Limited | Larger |
Q24. How are exceptions handled in C#?
Use try, catch, finally, and throw
try: Wrap code that may throw exceptions
catch: Handle specific exception
finally: Cleanup code executes always
throw: Throw exception
Q25. Difference between throw and throw ex
throw: Preserves original stack trace
throw ex: Resets stack trace
Q26. Difference between checked and unchecked exceptions in C#
"C# does not enforce checked exceptions; all exceptions are runtime exceptions. Developers handle exceptions using try-catch."
Q27. What is a delegate in C#?
"A delegate is a type-safe function pointer that can reference methods with a specific signature."
Q28. What is an event in C#?
"Event is a message sent by an object to signal the occurrence of an action. Events are based on delegates."
Q29. What is a lambda expression?
"Lambda expressions provide concise syntax to define anonymous functions. Often used with LINQ."
Example:
Func<int,int,int> add = (x,y) => x+y;
Q30. Difference between delegate and interface callback
Delegate: Type-safe, method signature specific
Interface: Must implement interface method; less flexible
Q31. Difference between Array and ArrayList
| Feature | Array | ArrayList |
|---|---|---|
| Type safety | Yes | No |
| Resize | Fixed | Dynamic |
| Performance | Faster | Slightly slower |
Q32. Difference between List<T> and ArrayList
List: Generic, type-safe, better performance
ArrayList: Non-generic, stores objects, boxing/unboxing
Q33. What is LINQ in C#?
"Language Integrated Query allows querying collections using SQL-like syntax integrated in C#."
Example:
var evenNumbers = numbers.Where(n => n % 2 == 0);
Q34. Difference between deferred execution and immediate execution in LINQ
Deferred: Query executed when enumerated (Where, Select)
Immediate: Query executed immediately (ToList(), Count())
Q35. What is a thread in C#?
"A thread is the smallest unit of execution. Multiple threads can run concurrently to perform parallel tasks."
Q36. Difference between Thread and Task in C#
Thread: Low-level control, manual management
Task: High-level abstraction, uses thread pool, supports async/await
Q37. What is async and await?
async: Marks a method as asynchronous
await: Waits for async task to complete without blocking
Q38. Difference between ref and out parameters
| Feature | ref | out |
|---|---|---|
| Initialization | Must be initialized before passing | Not required |
| Usage | Pass value to method and back | Pass value back only |
Q39. What is boxing and unboxing?
Boxing: Converts value type to object
Unboxing: Converts object back to value type
Q40. Difference between abstract and virtual methods
abstract: Must be overridden in derived class; no implementation in base
virtual: Can be overridden; has default implementation
Q41. Difference between is and as keywords
is: Checks type compatibility, returns bool
as: Attempts type conversion, returns null if fails
Q42. Difference between == and Equals()
==: Compares reference for reference types (can be overloaded)
Equals(): Compares object content; can be overridden
Q43. Difference between struct and class
| Feature | struct | class |
|---|---|---|
| Type | Value type | Reference type |
| Memory | Stack | Heap |
| Inheritance | Cannot inherit | Can inherit |
Q44. What is reflection in C#?
"Reflection allows inspecting assemblies, types, and members at runtime."
Q45. What are attributes in C#?
"Attributes provide metadata about program elements. Example: [Obsolete], [Serializable]."
Answer:
Object-Oriented: Classes, objects, inheritance, polymorphism
Type-Safe: Strong typing, compile-time checking
Garbage-Collected: Automatic memory management
Component-Oriented: Supports assemblies and reusable components
Interoperable: Can interact with COM objects and native code
Modern Constructs: LINQ, async/await, generics
Answer:
C#: Programming language
.NET Framework/Core/5+: Runtime and libraries supporting multiple languages including C#
Answer:
| Feature | Value Type | Reference Type |
|---|---|---|
| Memory | Stack | Heap |
| Copying | Copies value | Copies reference |
| Examples | int, double, struct | class, string, array |
Answer:
Boxing: Converts value type to object
Unboxing: Converts object back to value type
int x = 10; object obj = x; // Boxing
int y = (int)obj; // Unboxing
== and Equals()?Answer:
== compares reference equality for objects, value equality for value types
Equals() compares logical equality, can be overridden
Answer:
Allows value types to represent null
Syntax: int? x = null;
Useful in databases, optional fields, and APIs
const, readonly, and staticAnswer:
| Keyword | When Assigned | Mutable | Shared Across Instances |
|---|---|---|---|
| const | Compile-time | No | Yes |
| readonly | Runtime/Constructor | No | Optional |
| static | Runtime | Yes | Yes |
Answer:
Type-safe function pointer
Can point to methods with matching signature
Used for callbacks, events, LINQ
public delegate int MathOp(int a,int b);
MathOp op = (x,y) => x+y;
Answer:
Mechanism to notify subscribers when something happens
Events are based on delegates
public event EventHandler OnDataReceived;
abstract class and interfaceAnswer:
| Feature | Abstract Class | Interface |
|---|---|---|
| Implementation | Can have concrete methods | Only method signature (C# 8+ allows default) |
| Fields | Can have fields | No fields |
| Multiple Inheritance | Single | Multiple |
| Constructor | Allowed | Not allowed |
Answer:
Single Inheritance: class Child: Parent
Multilevel: GrandChild: Child: Parent
Hierarchical: Multiple classes inherit same base
Interface-based Multiple Inheritance: Implement multiple interfaces
Answer:
Compile-time (static): Method overloading, operator overloading
Runtime (dynamic): Method overriding using virtual and override
class Animal { public virtual void Speak() => Console.WriteLine("Animal"); }
class Dog: Animal { public override void Speak() => Console.WriteLine("Dog"); }
Answer:
Hiding data and providing access via properties or methods
Example:
private int age;
public int Age { get => age; set { if(value>0) age=value; } }
Answer:
Focus on what a class does, not how it does
Implemented via abstract classes or interfaces
virtual, override, and new keywordsAnswer:
virtual – base class method can be overridden
override – derived class overrides base virtual method
new – hides base class method, not override
sealed and static classAnswer:
sealed – Cannot be inherited
static – Cannot be instantiated, contains only static members
ref and out parameters?Answer:
| Feature | ref | out |
|---|---|---|
| Must be initialized before call | Yes | No |
| Pass value back | Yes | Yes |
| Usage | Passing existing variable | Returning multiple outputs |
class and structAnswer:
| Feature | Class | Struct |
|---|---|---|
| Type | Reference | Value |
| Heap/Stack | Heap | Stack |
| Inheritance | Supports | Does not support |
| Default Constructor | No | Yes (auto zero) |
interface and abstract class in real projectsAnswer:
Abstract class: Partial implementation, common code for derived classes
Interface: Defines a contract, allows multiple inheritance of behavior
Answer:
Allow objects to be indexed like arrays
class Sample { private int[] arr = new int[10]; public int this[int i] { get => arr[i]; set => arr[i]=value; } }
Answer:
Enables type-safe reusable code
Avoids boxing/unboxing
List<int> numbers = new List<int>();
Task, Thread, and async/awaitAnswer:
Thread – low-level OS thread
Task – abstraction of work unit, supports continuation
async/await – asynchronous programming with non-blocking I/O
Answer:
Language Integrated Query for collections, XML, databases
var evens = numbers.Where(n=>n%2==0).ToList();
IEnumerable and IQueryableAnswer:
| Feature | IEnumerable | IQueryable |
|---|---|---|
| Execution | In-memory | Database-side |
| Deferred Execution | Yes | Yes, optimized query |
| Provider | .NET objects | LINQ provider |
Array and List<T>Answer:
| Feature | Array | List |
|---|---|---|
| Size | Fixed | Dynamic |
| Methods | Limited | Rich API (Add, Remove, Contains) |
| Type-safety | Yes | Yes (generic) |
async and awaitAnswer:
async marks method as asynchronous
await waits for Task completion without blocking
Example:
async Task<int> FetchDataAsync() { return await httpClient.GetAsync(...); }
Task.Run and ThreadAnswer:
Task.Run – lightweight, uses thread pool, easier to manage
Thread – manually managed, OS-level threads, heavier
yield returnAnswer:
Returns elements one by one in lazy fashion
Reduces memory usage
IEnumerable<int> GetNumbers(){ for(int i=0;i<10;i++) yield return i; }
lock, Mutex, SemaphoreAnswer:
lock – exclusive access within same process
Mutex – exclusive across processes
Semaphore – allows limited concurrent access
== and Equals in C#Answer:
== – operator, compares references for objects unless overloaded
Equals() – logical comparison, can be overridden
Answer:
Tracks object references, frees memory for unreachable objects
Generational (0,1,2) for efficiency
Can use GC.Collect() manually but generally discouraged
Answer:
Managed: .NET objects handled by GC
Unmanaged: OS resources like file handles, DB connections; dispose via IDisposable
IDisposable and using statementAnswer:
Ensures deterministic release of unmanaged resources
using(var fs=new FileStream(...)){ ... }
stack and heap in C#Answer:
Stack: Local variables, faster, limited
Heap: Objects, slower, GC-managed
Answer:
Minimize boxing/unboxing
Use value types for small structs
Dispose unmanaged objects
Use pooling (object pools)
Answer:
Use constructor injection, property injection, or framework (e.g., Microsoft DI)
Promotes loose coupling and testability
Answer:
MemoryCache, DistributedCache (Redis), Response caching
Helps improve performance and reduce DB load
Answer:
lock, Monitor, Mutex, Semaphore
ConcurrentDictionary, ConcurrentQueue
Task-based async patterns
Answer:
Use ILogger in .NET Core
Log levels: Info, Debug, Warning, Error
Log to files, DB, or centralized system (ELK, Seq)
Answer:
RESTful conventions
Versioning, exception handling, consistent response structure
Logging, authentication/authorization
Caching, pagination, filtering
Answer:
Use deferred execution carefully
Avoid multiple enumerations
Use projection (Select) to fetch only required fields
For database queries, prefer IQueryable over IEnumerable
Answer:
Use xUnit, NUnit, MSTest
Mock dependencies via Moq
Test business logic independent of database or external services