C#

C#

Top Interview Questions

About C#

 

Understanding C# (C-Sharp)

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.


History and Evolution of C#

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.


Key Features of C#

C# is a high-level, multi-paradigm language designed for modern software development. Its main features include:

  1. Object-Oriented Programming (OOP): Supports encapsulation, inheritance, polymorphism, and abstraction.

  2. Type Safety: Strongly typed language that minimizes runtime errors.

  3. Automatic Memory Management: Uses garbage collection to manage memory automatically.

  4. Interoperability: Can interact with unmanaged code, COM objects, and native Windows APIs.

  5. Cross-Platform Development: With .NET Core and .NET 5/6/7, C# applications can run on multiple platforms.

  6. Asynchronous Programming: Supports async/await to handle I/O-bound tasks efficiently.

  7. Rich Standard Library: Provides extensive libraries for file handling, networking, database access, and graphics.

  8. LINQ Support: Language-Integrated Query allows querying collections and databases directly using C# syntax.

  9. Component-Oriented Programming: Facilitates the development of reusable software components.

  10. Modern Language Constructs: Features like tuples, nullable types, pattern matching, and records improve readability and maintainability.


C# Syntax and Structure

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.


Programming Paradigms in C#

C# supports multiple programming paradigms, making it versatile:

  1. Object-Oriented Programming (OOP): Classes and objects model real-world entities.

  2. Procedural Programming: Methods and functions support step-by-step instruction execution.

  3. Functional Programming: Lambda expressions, delegates, and LINQ enable functional patterns.

  4. Asynchronous Programming: Async and await keywords allow non-blocking operations.

  5. 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.


Core Concepts in C#

1. Classes and Objects

  • 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();

2. Inheritance

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!");
}

3. Polymorphism

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.


4. Encapsulation

Encapsulation protects class data using access modifiers like private, protected, and public.

class BankAccount
{
    private double balance;
    public void Deposit(double amount) => balance += amount;
}

5. Abstraction

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;
}

6. Delegates and Events

  • Delegates: Type-safe pointers to methods.

  • Events: Enable event-driven programming, widely used in GUI apps.


7. LINQ (Language Integrated Query)

LINQ allows querying collections elegantly:

int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);

Applications of C#

C# is widely used across industries due to its robustness, scalability, and integration with .NET:

  1. Web Development: ASP.NET Core for building dynamic web applications and APIs.

  2. Desktop Applications: Windows Forms and WPF for GUI-based software.

  3. Mobile Development: Xamarin allows cross-platform mobile apps using C#.

  4. Game Development: Unity engine uses C# for scripting and game logic.

  5. Cloud Computing: Azure development uses C# for cloud services and serverless functions.

  6. Enterprise Applications: Banking, ERP, and CRM systems rely heavily on C# and .NET.

  7. IoT Applications: Embedded devices and smart home systems use C# for connectivity and control.


Advantages of C#

  1. Simple and Modern: Easy-to-learn syntax with modern programming features.

  2. Object-Oriented: Encourages code reuse and modularity.

  3. Type-Safe: Minimizes runtime errors.

  4. Cross-Platform: Compatible with Windows, Linux, macOS, and mobile.

  5. Integrated with .NET: Access to libraries, tools, and frameworks.

  6. Robust Security: Supports strong typing, garbage collection, and code verification.

  7. Active Community: Large developer ecosystem with extensive documentation.


Disadvantages of C#

  1. Windows-Centric History: Although now cross-platform, it originally focused on Windows.

  2. Memory Management Overhead: Garbage collection may introduce minor delays.

  3. Less Control Over Hardware: Compared to C or C++, lower-level control is limited.

  4. Learning Curve: Advanced features like async, delegates, and LINQ can be challenging for beginners.


Future of C#

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.


Conclusion

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.

Fresher Interview Questions

 

1. Basics of C#

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."


2. Data Types & Variables

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


3. Object-Oriented Programming in C#

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; }
    }
}

4. Memory Management

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

5. Exception Handling

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."


6. Delegates, Events, and Lambda

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


7. Collections and LINQ

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())


8. Multi-threading

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


9. Miscellaneous

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]."

Experienced Interview Questions

 

Core C# Concepts

1. What are the main features of C#?

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


2. Difference between C# and .NET Framework

Answer:

  • C#: Programming language

  • .NET Framework/Core/5+: Runtime and libraries supporting multiple languages including C#


3. Difference between value type and reference type

Answer:

Feature Value Type Reference Type
Memory Stack Heap
Copying Copies value Copies reference
Examples int, double, struct class, string, array

4. What is boxing and unboxing?

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

5. What is the difference between == and Equals()?

Answer:

  • == compares reference equality for objects, value equality for value types

  • Equals() compares logical equality, can be overridden


6. What are nullable types?

Answer:

  • Allows value types to represent null

  • Syntax: int? x = null;

  • Useful in databases, optional fields, and APIs


7. Difference between const, readonly, and static

Answer:

Keyword When Assigned Mutable Shared Across Instances
const Compile-time No Yes
readonly Runtime/Constructor No Optional
static Runtime Yes Yes

8. What is a delegate in C#?

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;

9. What is an event in C#?

Answer:

  • Mechanism to notify subscribers when something happens

  • Events are based on delegates

public event EventHandler OnDataReceived;

10. Difference between abstract class and interface

Answer:

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

OOP Concepts

11. Explain inheritance types in C#

Answer:

  • Single Inheritance: class Child: Parent

  • Multilevel: GrandChild: Child: Parent

  • Hierarchical: Multiple classes inherit same base

  • Interface-based Multiple Inheritance: Implement multiple interfaces


12. What is polymorphism in C#?

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"); }

13. What is encapsulation in C#?

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; } }

14. What is abstraction in C#?

Answer:

  • Focus on what a class does, not how it does

  • Implemented via abstract classes or interfaces


15. Difference between virtual, override, and new keywords

Answer:

  • virtual – base class method can be overridden

  • override – derived class overrides base virtual method

  • new – hides base class method, not override


16. Difference between sealed and static class

Answer:

  • sealed – Cannot be inherited

  • static – Cannot be instantiated, contains only static members


17. What is the difference between 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

18. Difference between class and struct

Answer:

Feature Class Struct
Type Reference Value
Heap/Stack Heap Stack
Inheritance Supports Does not support
Default Constructor No Yes (auto zero)

19. What is the difference between interface and abstract class in real projects

Answer:

  • Abstract class: Partial implementation, common code for derived classes

  • Interface: Defines a contract, allows multiple inheritance of behavior


20. Explain indexers in C#

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; } }

Advanced Features

21. What are generics in C#?

Answer:

  • Enables type-safe reusable code

  • Avoids boxing/unboxing

List<int> numbers = new List<int>();

22. Difference between Task, Thread, and async/await

Answer:

  • Thread – low-level OS thread

  • Task – abstraction of work unit, supports continuation

  • async/await – asynchronous programming with non-blocking I/O


23. What is LINQ?

Answer:

  • Language Integrated Query for collections, XML, databases

var evens = numbers.Where(n=>n%2==0).ToList();

24. Difference between IEnumerable and IQueryable

Answer:

Feature IEnumerable IQueryable
Execution In-memory Database-side
Deferred Execution Yes Yes, optimized query
Provider .NET objects LINQ provider

25. Difference between Array and List<T>

Answer:

Feature Array List
Size Fixed Dynamic
Methods Limited Rich API (Add, Remove, Contains)
Type-safety Yes Yes (generic)

26. Explain async and await

Answer:

  • async marks method as asynchronous

  • await waits for Task completion without blocking

  • Example:

async Task<int> FetchDataAsync() { return await httpClient.GetAsync(...); }

27. Difference between Task.Run and Thread

Answer:

  • Task.Run – lightweight, uses thread pool, easier to manage

  • Thread – manually managed, OS-level threads, heavier


28. Explain yield return

Answer:

  • Returns elements one by one in lazy fashion

  • Reduces memory usage

IEnumerable<int> GetNumbers(){ for(int i=0;i<10;i++) yield return i; }

29. Difference between lock, Mutex, Semaphore

Answer:

  • lock – exclusive access within same process

  • Mutex – exclusive across processes

  • Semaphore – allows limited concurrent access


30. Difference between == and Equals in C#

Answer:

  • == – operator, compares references for objects unless overloaded

  • Equals() – logical comparison, can be overridden


Memory Management & Performance

31. How does Garbage Collector work in C#?

Answer:

  • Tracks object references, frees memory for unreachable objects

  • Generational (0,1,2) for efficiency

  • Can use GC.Collect() manually but generally discouraged


32. Difference between managed and unmanaged resources

Answer:

  • Managed: .NET objects handled by GC

  • Unmanaged: OS resources like file handles, DB connections; dispose via IDisposable


33. What is IDisposable and using statement

Answer:

  • Ensures deterministic release of unmanaged resources

using(var fs=new FileStream(...)){ ... }

34. Difference between stack and heap in C#

Answer:

  • Stack: Local variables, faster, limited

  • Heap: Objects, slower, GC-managed


35. How to optimize memory in C# applications

Answer:

  • Minimize boxing/unboxing

  • Use value types for small structs

  • Dispose unmanaged objects

  • Use pooling (object pools)


Practical / Scenario-Based

36. How do you implement dependency injection?

Answer:

  • Use constructor injection, property injection, or framework (e.g., Microsoft DI)

  • Promotes loose coupling and testability


37. How do you implement caching in C# APIs?

Answer:

  • MemoryCache, DistributedCache (Redis), Response caching

  • Helps improve performance and reduce DB load


38. How do you handle concurrency in C#?

Answer:

  • lock, Monitor, Mutex, Semaphore

  • ConcurrentDictionary, ConcurrentQueue

  • Task-based async patterns


39. How do you implement logging?

Answer:

  • Use ILogger in .NET Core

  • Log levels: Info, Debug, Warning, Error

  • Log to files, DB, or centralized system (ELK, Seq)


40. How do you design a robust API in C#?

Answer:

  • RESTful conventions

  • Versioning, exception handling, consistent response structure

  • Logging, authentication/authorization

  • Caching, pagination, filtering


41. How do you optimize LINQ queries?

Answer:

  • Use deferred execution carefully

  • Avoid multiple enumerations

  • Use projection (Select) to fetch only required fields

  • For database queries, prefer IQueryable over IEnumerable


42. How do you implement unit testing in C#?

Answer:

  • Use xUnit, NUnit, MSTest

  • Mock dependencies via Moq

  • Test business logic independent of database or external services