C# Interview Questions & Answers E-book
Question 1 :- Explain difference between .NET and C# ?
.NET is a framework developed by Microsoft that provides a controlled environment for developing and running applications. It includes a large class library known as the Framework Class Library (FCL) and provides language interoperability across several programming languages. C# is a programming language developed by Microsoft that runs on the .NET framework. It is used to write applications that run on the .NET framework.
Question 2 :- .NET Framework vs .NET Core vs .NET 5.0
.NET Framework is the original implementation of .NET, which is Windows-only. .NET Core is a cross-platform, open-source version of .NET for building websites, services, and console apps. .NET 5.0 is the next step in the evolution of .NET, combining the best of .NET Framework and .NET Core into a single platform that is cross-platform and open-source.
Question 3 :- What is IL ( Intermediate Language) Code ?
Intermediate Language (IL) is the CPU-independent instruction set into which .NET source code is compiled. IL code is then converted to machine code by the Just-In-Time (JIT) compiler at runtime.
Question 4 :- What is the use of JIT ( Just in time compiler) ?
The Just-In-Time (JIT) compiler converts the Intermediate Language (IL) code into native machine code that the CPU can execute. This conversion happens at runtime, just before the code is executed.
Question 5 :- Is it possible to view IL code ?
Yes, it is possible to view IL code using tools like ILDASM (IL Disassembler) or ILSpy. These tools allow you to inspect the IL code generated by the .NET compiler.
Question 6 :- What is the benefit of compiling in to IL code ?
Compiling to IL code allows .NET applications to be platform-independent. The IL code can be executed on any platform that has a .NET runtime, which then compiles the IL code to native machine code specific to that platform.
Question 7 :- Does .NET support multiple programming languages ?
Yes, .NET supports multiple programming languages, including C#, VB.NET, F#, and more. This is possible because all .NET languages compile to the same Intermediate Language (IL) code.
Question 8 :- What is CLR ( Common Language Runtime) ?
The Common Language Runtime (CLR) is the virtual machine component of the .NET framework. It manages the execution of .NET programs, providing services such as memory management, security, and exception handling.
Question 9 :- What is managed and unmanaged code ?
Managed code is code that runs under the control of the CLR, which provides services like garbage collection and type safety. Unmanaged code is code that runs outside the control of the CLR, typically written in languages like C or C++.
Question 10 :- Explain the importance of Garbage collector ?
The garbage collector (GC) in .NET automatically manages memory allocation and deallocation. It helps to prevent memory leaks by reclaiming memory that is no longer in use, thus improving the performance and reliability of applications.
Question 11 :- Can garbage collector claim unmanaged objects ?
No, the garbage collector cannot directly manage unmanaged objects. However, it can manage objects that contain references to unmanaged resources and can call the appropriate cleanup code (such as finalizers) to release those resources.
Question 12 :- What is the importance of CTS(Common Types System) ?
The Common Type System (CTS) defines how types are declared, used, and managed in the runtime. It ensures that objects written in different .NET languages can interact with each other, providing a unified type system across all .NET languages.
Question 13 :- Explain CLS ?
The Common Language Specification (CLS) is a set of rules that apply to all languages targeting the .NET framework. It ensures that code written in one .NET language can be used by other .NET languages, promoting language interoperability.
Question 14 :- Difference between Stack vs Heap ?
The stack is used for static memory allocation and is managed by the CPU. It stores value types and the references to objects. The heap is used for dynamic memory allocation and is managed by the garbage collector. It stores objects and reference types.
Question 15 :- What are Value types & Reference types?
Value types are types that hold their value in memory where they are declared. Examples include int, char, and struct. Reference types store a reference to their data (objects) in memory. Examples include class, array, and string.
Question 16 :- Explain boxing and unboxing ?
Boxing is the process of converting a value type to a reference type by wrapping the value inside an object. Unboxing is the process of extracting the value type from the object. Boxing and unboxing can impact performance due to the additional overhead.
Question 17 :- What is consequence of boxing and unboxing ?
Boxing and unboxing can lead to performance issues because they involve additional memory allocation and copying of data. Frequent boxing and unboxing can result in increased garbage collection and reduced application performance.
Question 18 :- Explain casting, implicit casting and explicit casting ?
Casting is the process of converting one type to another. Implicit casting is automatically performed by the compiler when there is no risk of data loss. Explicit casting requires a cast operator and is used when there is a risk of data loss or when converting between incompatible types.
Question 19 :- What can happen during explicit casting ?
During explicit casting, if the conversion is not valid, it can result in a runtime exception (InvalidCastException). It is important to ensure that the types are compatible and the conversion is valid to avoid exceptions.
Question 20 :- Differentiate between Array and ArrayList ?
An array is a fixed-size collection of elements of the same type. ArrayList is a dynamic array that can grow and shrink in size and can hold elements of different types. Arrays provide better performance, while ArrayLists offer more flexibility.
Question 21 :- Whose performance is better array or arraylist ?
Arrays generally offer better performance than ArrayLists because they have a fixed size and do not require dynamic resizing. ArrayLists, being dynamic, involve additional overhead for resizing and type checking.
Question 22 :- What are generic collections ?
Generic collections are type-safe collections that allow you to define the type of elements they can hold. Examples include List, Dictionary, and Queue. They provide better performance and type safety compared to non-generic collections.
Question 23 :- What are threads (Multithreading)?
Threads are the smallest unit of execution within a process. Multithreading allows multiple threads to run concurrently, enabling parallel execution of tasks and improving application performance and responsiveness.
Question 24 :- How are threads different from TPL(Task Parallel Library) ?
The Task Parallel Library (TPL) is a higher-level abstraction for parallel programming in .NET. It simplifies the creation and management of threads by providing a task-based model. TPL handles thread pooling, scheduling, and synchronization, making it easier to write concurrent code.
Question 25 :- How do we handle exceptions in C#(try/catch)?
Exceptions in C# are handled using try/catch blocks. Code that may throw an exception is placed inside a try block, and the catch block contains code to handle the exception. Multiple catch blocks can be used to handle different types of exceptions.
Question 26 :- What is the need of finally?
The finally block is used to execute code that must run regardless of whether an exception is thrown or not. It is typically used for cleanup operations, such as closing files or releasing resources, ensuring that these actions are performed even if an exception occurs.
Question 27 :- Why do we need the out keyword ?
The out keyword is used to pass arguments to methods by reference, allowing the method to modify the value of the argument. It is commonly used when a method needs to return multiple values or when the value of the argument needs to be initialized within the method.
Question 28 :- What is the need of Delegates ?
Delegates are used to encapsulate a method reference, allowing methods to be passed as parameters and invoked dynamically. They are essential for implementing event handling, callback methods, and designing extensible and flexible applications.
Question 29 :- What are events ?
Events are a way for objects to communicate with each other. They are based on delegates and provide a mechanism for broadcasting notifications to multiple subscribers. Events are commonly used in GUI applications to handle user actions like button clicks.
Question 30 :- Whats the difference between Abstract class and interface ?
An abstract class can have both abstract methods (without implementation) and concrete methods (with implementation). An interface can only have method declarations (without implementation). A class can inherit from multiple interfaces but only one abstract class.
Question 31 - What is a Delegate and how to create a Delegate?
A delegate is a type that represents references to methods with a specific parameter list and return type. To create a delegate, you define a delegate type and then create an instance of the delegate, assigning it a method with a matching signature.
Question 32 - Where have you used Delegates?
Delegates are commonly used in event handling, callback methods, and designing extensible frameworks. For example, in a GUI application, delegates are used to handle button click events by assigning event handler methods to the button's Click event.
Question 33 - What is a Multicast Delegates?
A multicast delegate is a delegate that can hold references to multiple methods. When invoked, it calls all the methods in its invocation list. Multicast delegates are useful for implementing event handling, where multiple subscribers need to be notified of an event.
Question 34 - What is an Event?
An event is a mechanism for communication between objects. It is based on delegates and allows a class to notify other classes when something of interest occurs. Events are commonly used in GUI applications to handle user actions like button clicks.
Question 35 - How to Create an Event?
To create an event, you define a delegate type and then declare an event of that delegate type. You can then add or remove event handlers using the += and -= operators. The event can be raised by calling the delegate.
Question 36 - Delegate VS Events.
Delegates are function pointers that can hold references to methods. Events are a higher-level abstraction built on delegates, providing a mechanism for broadcasting notifications to multiple subscribers. Events add additional constraints, such as only allowing += and -= operations.
Question 37 :- Why do we need Object Oriented Programming (OOP) ?
Object-Oriented Programming (OOP) provides a structured approach to software development by organizing code into reusable and maintainable objects. It promotes code reuse, encapsulation, inheritance, and polymorphism, making it easier to manage and extend complex applications.
Question 38 :- What are the important pillars of OOPs ?
The four main pillars of OOP are:
Encapsulation: Bundling data and methods that operate on the data within a single unit (class).
Abstraction: Hiding complex implementation details and exposing only the necessary features.
Inheritance: Creating new classes based on existing classes, promoting code reuse.
Polymorphism: Allowing objects to be treated as instances of their parent class, enabling dynamic method binding.
Question 39 :- What is a class and object ?
A class is a blueprint for creating objects, defining the properties and methods that the objects will have. An object is an instance of a class, representing a specific entity with its own state and behavior.
Question 40 :- Abstraction vs Encapsulation?
Abstraction is the concept of hiding complex implementation details and exposing only the necessary features. Encapsulation is the practice of bundling data and methods that operate on the data within a single unit (class) and restricting access to the internal state.
Question 41 :- Explain Inheritance ?
Inheritance is a mechanism in OOP that allows a new class (derived class) to inherit properties and methods from an existing class (base class). It promotes code reuse and establishes a hierarchical relationship between classes.
Question 42 :- Explain virtual keyword ?
The virtual keyword is used to declare a method or property in a base class that can be overridden in a derived class. It allows derived classes to provide a specific implementation for the method or property.
Question 43 :- What is overriding ?
Overriding is the process of providing a new implementation for a virtual method or property in a derived class. The new implementation replaces the base class implementation when the method or property is called on an instance of the derived class.
Question 44 :- Explain overloading ?
Overloading is the process of defining multiple methods with the same name but different parameter lists within the same class. It allows methods to be called with different arguments, providing flexibility in method usage.
Question 45 :- Overloading vs Overriding ?
Overloading allows multiple methods with the same name but different parameter lists within the same class. Overriding allows a derived class to provide a new implementation for a virtual method or property defined in a base class.
Question 46 :- What is polymorphism ?
Polymorphism is the ability of objects to be treated as instances of their parent class, allowing methods to be called on objects of different types. It enables dynamic method binding and promotes code flexibility and reuse.
Question 47 :- Can polymorphism work with out inheritance ?
No, polymorphism relies on inheritance to allow objects to be treated as instances of their parent class. Without inheritance, there would be no hierarchical relationship between classes, and polymorphism would not be possible.
Question 48 :- Explain static vs dynamic polymorphism ?
Static polymorphism, also known as compile-time polymorphism, is achieved through method overloading and operator overloading. Dynamic polymorphism, also known as runtime polymorphism, is achieved through method overriding and interfaces.
Question 49 :- Explain operator overloading ?
Operator overloading allows you to define custom behavior for operators (such as +, -, *, etc.) for user-defined types. It enables operators to be used with objects of those types, providing a more intuitive and readable syntax.
Question 50 :- Why do we need Abstract classes ?
Abstract classes provide a way to define common behavior and properties for related classes while allowing derived classes to provide specific implementations. They cannot be instantiated and are used to create a base class that other classes can inherit from.
Question 51 :- Are Abstract methods virtual ?
Yes, abstract methods are implicitly virtual. They must be overridden in derived classes, providing a way to enforce a contract for derived classes to implement specific methods.
Question 52 :- Can we create a instance of Abstract classes ?
No, abstract classes cannot be instantiated directly. They are meant to be used as base classes for other classes to inherit from and provide specific implementations for abstract methods.
Question 53 :- Is it compulsory to implement Abstract methods ?
Yes, it is compulsory for derived classes to implement all abstract methods defined in the abstract class. Failure to do so will result in a compilation error.
Question 54 :- Why can’t simple base class replace Abstract class ?
A simple base class can provide default implementations for methods, but it cannot enforce that derived classes implement specific methods. Abstract classes provide a way to define a contract that derived classes must follow, ensuring consistency and completeness.
Question 55 :- Explain interfaces and why do we need it ?
Interfaces define a contract that classes must follow, specifying methods and properties without providing implementations. They promote loose coupling and allow for multiple inheritance, enabling classes to implement multiple interfaces and providing greater flexibility in design.
Question 56 :- Can we write logic in interface ?
No, interfaces cannot contain implementation logic. They can only contain method and property declarations. Implementation logic must be provided by the classes that implement the interface.
Question 57 :- Can we define methods as private in interface ?
No, all methods and properties in an interface are implicitly public. Interfaces are meant to define a public contract that classes must follow, so private members are not allowed.
Question 58 :- If I want to change interface what's the best practice ?
If you need to change an interface, the best practice is to create a new interface with the required changes and have the existing interface extend the new interface. This approach maintains backward compatibility and allows existing implementations to continue working.
Question 59 :- Explain Multiple inheritance in Interface ?
Multiple inheritance in interfaces allows a class to implement multiple interfaces, inheriting the contracts defined by each interface. This provides greater flexibility and allows a class to combine behaviors from multiple sources.
Question 60 :- Explain Interface Segregation principle ?
The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. It states that no client should be forced to depend on methods it does not use. This means that interfaces should be small and specific, containing only the methods that are relevant to the client.
Question 61 :- Can we create instance of interface ?
No, you cannot create an instance of an interface directly. Interfaces define a contract that classes must implement. You can create an instance of a class that implements the interface and use it through the interface reference.
Question 62 :- Can we do Multiple inheritance with Abstract classes ?
No, C# does not support multiple inheritance with classes, including abstract classes. A class can inherit from only one base class. However, a class can implement multiple interfaces, which allows for a form of multiple inheritance.
Question 63 :- Abstract Class vs Interface
Abstract classes can have both abstract and concrete methods, while interfaces can only have method declarations. A class can inherit from only one abstract class but can implement multiple interfaces. Abstract classes are used when classes share a common base, while interfaces are used to define a contract that multiple classes can implement.
Question 64 :- Why do we need constructors ?
Constructors are special methods that are called when an object is instantiated. They are used to initialize the object's state, setting initial values for fields and performing any setup required for the object to function correctly.
Question 65 :- In parent child which constructor fires first ?
In a parent-child class relationship, the constructor of the parent class (base class) is called first, followed by the constructor of the child class (derived class). This ensures that the base class is properly initialized before the derived class.
Question 66 :- How are initializers executed ?
Initializers are executed in the order they appear in the class definition, before the constructor is called. This applies to both field initializers and property initializers. If a field or property is initialized both in the initializer and the constructor, the initializer runs first.
Question 67 :- How are static constructors executed in Parent child ?
Static constructors are executed once per type, before any static members are accessed or any instances of the type are created. In a parent-child class relationship, the static constructor of the base class is executed first, followed by the static constructor of the derived class.
Question 68 :- When does static constructor fires ?
A static constructor is called automatically before any static members are accessed or any instances of the class are created. It is used to initialize static fields or perform actions that need to be done only once for the class.
Question 69: - Explain Garbage collector (GC)?
The Garbage Collector (GC) in .NET is responsible for automatic memory management. It periodically checks for objects that are no longer in use and reclaims their memory, freeing it for future allocations. This helps to prevent memory leaks and manage memory efficiently.
Question 70:- How does Garbage collector know when to clean the objects ?
The Garbage Collector (GC) uses a process called "mark-and-sweep" to determine which objects are no longer in use. It marks all objects that are reachable from the root references (such as static fields, local variables, and CPU registers). Objects that are not marked are considered unreachable and are collected.
Question 71:- Explain weak and strong references ?
A strong reference is a normal reference that prevents the referenced object from being collected by the garbage collector. A weak reference, on the other hand, does not prevent the object from being collected. Weak references are useful for caching scenarios where you want to keep an object in memory only if it is still being used elsewhere.
Question 72 :- When will you use weak references ?
Weak references are used in scenarios where you want to cache objects without preventing them from being collected by the garbage collector. This is useful for large objects that are expensive to create but can be recreated if needed, such as images or data retrieved from a database.
Question 73:- What are design patterns?
Design patterns are reusable solutions to common problems in software design. They provide a template for how to solve a problem in a way that is proven to be effective. Design patterns help to improve code readability, maintainability, and flexibility.
Question 74 :- Which are the different types of design patterns?
Design patterns are generally categorized into three types:
Creational Patterns: Deal with object creation mechanisms (e.g., Singleton, Factory, Abstract Factory).
Structural Patterns: Deal with object composition and relationships (e.g., Adapter, Composite, Decorator).
Behavioral Patterns: Deal with object interaction and responsibility (e.g., Observer, Strategy, Command).
Question 75 :- Explain structural , Behavioral and Creational design pattern ?
Structural Patterns: These patterns deal with object composition and relationships. Examples include Adapter, Composite, and Decorator. They help to ensure that if one part of a system changes, the entire system doesn't need to change.
Behavioral Patterns: These patterns deal with object interaction and responsibility. Examples include Observer, Strategy, and Command. They help to manage complex control flows and communication between objects.
Creational Patterns: These patterns deal with object creation mechanisms. Examples include Singleton, Factory, and Abstract Factory. They help to create objects in a manner suitable to the situation, ensuring that the system is flexible and reusable.
Question 76 :- Which design pattern have you used in your project?
The answer to this question will vary depending on the specific project and its requirements. Commonly used design patterns include Singleton for ensuring a class has only one instance, Factory for creating objects without specifying the exact class, and Observer for implementing event handling systems.
Question 77 :- Explain Singleton Pattern and the use of the same?
The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it. It is useful in scenarios where a single instance of a class is needed to coordinate actions across the system, such as a configuration manager or a logging class.
Question 78 :- How did you implement singleton pattern?
The Singleton Pattern can be implemented by creating a class with a private constructor, a private static instance of the class, and a public static method that returns the instance. The instance is created only once, ensuring that only one instance of the class exists.
public class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Question 79 :- Can we use Static class rather than using a private constructor?
Yes, a static class can be used to implement a Singleton pattern. However, static classes cannot implement interfaces or inherit from other classes, which limits their flexibility. Using a private constructor with a static instance provides more control and flexibility.
Question 80:- Static vs Singleton pattern?
A static class is a class that cannot be instantiated and contains only static members. A Singleton pattern ensures that a class has only one instance and provides a global point of access to it. Singleton allows for lazy initialization and can implement interfaces, while static classes cannot.
Question 81:- How did you implement thread safety in Singleton?
Thread safety in Singleton can be implemented using a lock mechanism to ensure that only one thread can create the instance at a time. This prevents multiple threads from creating multiple instances of the Singleton class.
public class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Question 82:- What is double null check in Singleton?
Double null check is a technique used to ensure thread safety in Singleton implementation. It involves checking if the instance is null before acquiring the lock and then checking again inside the lock to ensure that only one instance is created.
public class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
Question 83:- Can Singleton pattern code be made easy with Lazy keyword?
Yes, the Singleton pattern can be simplified using the Lazy<T> type, which provides lazy initialization and thread safety. The Lazy<T> type ensures that the instance is created only when it is needed and handles the thread safety internally.
public class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
private Singleton() { }
public static Singleton Instance
{
get
{
return lazy.Value;
}
}
}
Question 84:- Can we rid of this double null check code?
Yes, using the Lazy<T> type, you can avoid the double null check code. The Lazy<T> type handles the lazy initialization and thread safety, simplifying the Singleton implementation.
Question 85:- What is the use of repository pattern?
The Repository pattern is used to abstract the data access layer, providing a clean separation between the data access logic and the business logic. It allows for easier testing, maintenance, and flexibility in changing the data source without affecting the business logic.
Question 86:- Is Dal (Data access Layer) and Repository same?
The Data Access Layer (DAL) is a broader concept that includes all the data access logic, while the Repository pattern is a specific design pattern used within the DAL. The Repository pattern provides a more structured and testable way to access data.
Question 87:- What is Generic repository pattern ?
The Generic Repository pattern is a variation of the Repository pattern that uses generics to provide a common data access interface for all entities. It reduces code duplication and provides a more flexible and reusable data access layer.
public interface IRepository<T> where T : class
{
IEnumerable<T> GetAll();
T GetById(int id);
void Insert(T entity);
void Update(T entity);
void Delete(int id);
}
public class Repository<T> : IRepository<T> where T : class
{
private readonly DbContext context;
private readonly DbSet<T> dbSet;
public Repository(DbContext context)
{
this.context = context;
this.dbSet = context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return dbSet.ToList();
}
public T GetById(int id)
{
return dbSet.Find(id);
}
public void Insert(T entity)
{
dbSet.Add(entity);
context.SaveChanges();
}
public void Update(T entity)
{
dbSet.Attach(entity);
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges();
}
public void Delete(int id)
{
T entity = dbSet.Find(id);
dbSet.Remove(entity);
context.SaveChanges();
}
}
Question 88:- Is abstraction the only benefit of Repository?
No, abstraction is not the only benefit of the Repository pattern. Other benefits include:
Improved testability: The repository can be easily mocked for unit testing.
Separation of concerns: It separates the data access logic from the business logic.
Flexibility: It allows for easy changes to the data source without affecting the business logic.
Code reuse: It reduces code duplication by providing a common data access interface.