Get ready to crack any .NET interview with our comprehensive list of the most frequently asked .NET interview questions and answers for 2023.
The demand for proficient .NET developers is high, leading to stiff competition and many job openings. To help you prepare for your .NET interview, we’ve created a guide that includes expert advice and answers to commonly asked questions.
Our guide is carefully curated to provide in-depth knowledge and valuable insights for job seekers.

.NET Interview Questions
1. How does the .NET framework work?
The .NET Framework is a software framework developed by Microsoft. It provides a platform for building and running Windows-based applications. It includes a large library of pre-built components and classes that can be used to develop a wide range of applications. That includes desktop applications, web applications, and mobile apps.
- Applications written in languages such as C#, F#, or Visual Basic and based on the .NET framework are compiled into Common Intermediate Language (CIL).
- Compiled code is stored in the form of an assembly file that has a .dll or .exe file extension.
- During runtime of a .NET application, the Common Language Runtime (CLR) uses the Just-In-Time (JIT) compiler to convert the CIL into machine code.
- After the conversion process, the resulting machine code can run efficiently on the computer’s specific architecture.

2. Explain about major components of the .NET framework.
Here are some of the key components of the .NET Framework:
- Common Language Runtime (CLR):
- It is responsible for executing the code and providing various services that simplify the development process.
- These services include memory management, garbage collection, type safety, exception handling, security, and thread management.
- The CLR also makes it easier to design applications and components with objects that interact across different programming languages.
- Additionally, the CLR is used to execute programs written for the .NET Framework, regardless of the programming language used.
- Finally, each version of the .NET Framework includes its own version of the CLR.
- Framework Class Library(FCL):
- It has pre-defined methods and properties to implement common and complex functions that can be used by .NET applications. It will also provide types for dates, strings, numbers, etc.
- This class library includes APIs for database connection, file reading and writing, drawing, etc.
- Base Class Library(BCL):
- The Base Class Library (BCL) contains an extensive collection of library features and functions that are useful for implementing various programming languages within the .NET Framework, including C#, F#, Visual C++, and more.
- The BCL is divided into two parts:
- User-defined class library: It includes Assemblies.
- In the .NET Framework, an assembly is considered the main building block. An assembly in the Common Language Infrastructure (CLI) is a logical unit of code used for deployment, versioning, and security. There are two forms of an assembly: Dynamic Link Library (
.dll
) and executable (.exe
) files. When a .NET program is compiled, metadata with Microsoft Intermediate Language (MSIL) is generated and stored in an assembly file.
- In the .NET Framework, an assembly is considered the main building block. An assembly in the Common Language Infrastructure (CLI) is a logical unit of code used for deployment, versioning, and security. There are two forms of an assembly: Dynamic Link Library (
- Predefined class library: It contains namespace.
- In the .NET Framework, a namespace is a collection of predefined methods and classes. A namespace can be added to a .NET program using the
using system
syntax, whereusing
is a keyword andsystem
is the namespace.
- In the .NET Framework, a namespace is a collection of predefined methods and classes. A namespace can be added to a .NET program using the
- User-defined class library: It includes Assemblies.
- Common Type System(CTS):
- The Common Type System (CTS) is a standard that specifies which types of data and values can be defined and managed in memory during runtime.
- It ensures that programming data defined in different languages can interact with each other for sharing information. For example, in VB.NET, we define the datatype as integer, while in C#, we define int as a datatype.
- This ensures that data loss is prevented when transferring data from one language’s type to its equivalent type in another language.
- Common Language Specification (CLS):
- The Common Language Specification (CLS) is a set of guidelines that every language under the .NET framework must follow to ensure interoperability.
- CLS is a subset of the Common Type System (CTS) and defines a set of rules that should be followed by every .NET Framework’s language.
- CLS provides a common platform for sharing information and interacting with different programming languages in the .NET framework. For example, statements belonging to different languages can be executed on a common platform provided by the CLS.

3. What is JIT?
JIT stands for Just-In-Time compiler. It is a component of the .NET runtime environment.
When a .NET application is executed, the CIL (Common Intermediate Language) code generated by the compiler is not directly executed by the computer’s processor. Instead, the JIT compiler takes the CIL code and compiles it into native machine code that can be executed by the processor. This compilation happens at runtime, just before the code is executed, hence the name “Just-In-Time”. The JIT compiler also optimizes the code for better performance, based on the specific architecture of the computer it is running on.
4. What is the difference between managed and unmanaged code?
Managed Code | Unmanaged Code |
---|---|
Runs in a managed environment with a runtime (e.g., .NET Framework) | Runs natively on the operating system |
Code is compiled to an intermediate language (IL) before execution | Code is compiled to machine code before execution |
Memory is managed by the runtime through automatic garbage collection | Memory must be manually allocated and deallocated by the programmer |
Provides additional security features, such as type safety and automatic bounds checking | Does not provide type safety or automatic bounds checking |
Typically slower execution speed compared to unmanaged code | Typically faster execution speed compared to managed code |
Examples: C#, VB.NET, F# | Examples: C, C++, Assembly |
5. What is a garbage collector?
A garbage collector is a component of the .NET runtime that manages memory allocation and deallocation for .NET applications. Its primary function is to automatically reclaim memory that is no longer being used by an application.
- Generation 0: It holds short-lived objects.
- Generation 1: It stores medium-lived objects.
- Generation 2: This is for long-lived objects.
Collection of garbage refers to checking for objects in the generations of the managed heap that are no longer being used by the application. It also performs the necessary operations to reclaim their memory. The garbage collector must perform a collection in order to free some memory space.
When the garbage collector runs, it performs the following actions:
- It identifies the list of live objects that are still being used by the application.
- It updates the references for the compacted objects.
- It reclaims the memory space that was occupied by dead objects.
- The surviving objects are moved to an older segment of the heap.
In .NET, garbage collection can be triggered manually by calling the System.GC.Collect()
method.
6. What is an EXE and a DLL?
EXE files are standalone executable files that are capable of running independently on a computer. They are designed to perform a specific task or set of tasks. They are often used to install software or run programs. An EXE file can contain all the resources required to run a program, such as code, data, and user interface elements. When an EXE file is executed, it creates a new process in the operating system.
DLL files are shared libraries that contain code, data, and resources that can be used by multiple programs at the same time. They are designed to reduce the size of programs and improve their performance. By allowing multiple programs to use the same code and resources. DLL files are loaded into memory when they are needed by a program and can be unloaded when they are no longer needed. This allows multiple programs to share the same code and resources, which can reduce memory usage and improve performance.
Here’s a table summarizing the differences between EXE and DLL
Feature | EXE | DLL |
---|---|---|
Execution | Runs independently | Loaded by other programs |
Standalone | Yes | No |
Size | Larger | Smaller |
Resource sharing | No | Yes |
Code sharing | No | Yes |
Memory usage | Higher | Lower |
Note: The exact differences may vary depending on the specific use case and context.
7. How many languages are supported by .NET?
Some of the popular languages supported by .NET are:
- C#
- Visual Basic .NET (VB.NET)
- F#
- C++/CLI
- J#
- PowerShell
In addition to these, there are many other programming languages that can be used with .NET.
C# Interview Questions
8. What is C#?
C# is a modern, object-oriented programming language. It is developed by Microsoft as part of the .NET Framework. It is designed to be simple, efficient, and easy to use, while also offering advanced features for building complex applications.
C# is based on the C programming language. So, it easy for developers who are familiar with C or C++ to learn. C# also includes many features that are not found in C or C++. For example, garbage collection, type safety, and other object-oriented programming concepts.
C# code is compiled into an intermediate language (IL) that is then executed by the .NET runtime, which manages memory, security, and other system-level services.
9. What is the difference between int
and Int32
?
In .NET, int
and Int32
are aliases for the same underlying data type. They both represent a 32-bit signed integer.
The int
keyword is a C# language-specific alias for System.Int32
, whereas Int32
is the fully qualified name of the data type in the .NET Framework.
In other words, int
and Int32
can be used interchangeably in C# code, and they both represent the same data type. It is just a matter of personal preference which one to use.
10. Explain the differences between value type and reference type.
In .NET, types can be categorized into two broad categories – Value Types and Reference Types. The main differences between these two types are:
# | Value Types | Reference Types |
---|---|---|
Definition | Contain their data directly | Contain a reference to their data |
Memory Allocation | Stack | Heap |
Assignment | Copied by value | Copied by reference |
Lifetime | Short | Long |
Memory Management | Handled by the system | Handled by the garbage collector |
Examples | int, float, bool, struct | string, object, class, interface |
Note: The table is not exhaustive and there may be some exceptions to the general rules outlined above.
11. What is boxing and unboxing in .NET?
Boxing: This is the process of converting a value type to an object reference type.
Unboxing: This is the process of converting an object reference type to a value type.
Here’s an example of how boxing and unboxing work:
int myInt = 42; // Declare an int variable object boxedInt = myInt; // Box the int variable by assigning it to an object reference type int unboxedInt = (int)boxedInt; // Unbox the object reference type by casting it back to an int variable
In this example, myInt
is a value type and boxedInt
is a reference type that contains a copy of the myInt
value. unboxedInt
is a value type that is assigned the value of boxedInt
after it has been unboxed.
12. What is an event?
In .NET, an event is a mechanism for communication between objects, where an object can notify other objects when something of interest occurs. An event can be defined as a delegate with an associated event handler method that is called when the event is triggered.
In simpler terms, an event is a notification that is sent by an object to other objects, telling them that something has happened. For example, when a button is clicked, an event is raised by the button object, and the associated event handler method is called to perform the necessary actions.
Here is an example of an event in C#:
using System; class Program { static void Main(string[] args) { // Create an instance of the publisher class Publisher publisher = new Publisher(); // Subscribe to the event publisher.MyEvent += new EventHandler(MyEventHandler); // Raise the event publisher.RaiseMyEvent(); } static void MyEventHandler(object sender, EventArgs e) { Console.WriteLine("Event handled!"); } } class Publisher { // Declare the event public event EventHandler MyEvent; // Method to raise the event public void RaiseMyEvent() { if (MyEvent != null) MyEvent(this, EventArgs.Empty); } }
In this example, a class named Publisher
defines an event named MyEvent
of type EventHandler
. An instance of Publisher
is created in the Main
method and a method named MyEventHandler
is subscribed to the MyEvent
event using the +=
operator.
The RaiseMyEvent
method of the Publisher
class is called which checks whether the MyEvent
event is null or not. If it’s not null, the MyEvent
event is raised by passing the instance of the Publisher
class (this
) and an empty EventArgs
object to the MyEventHandler
method, which handles the event by writing a message to the console.
13. What is a delegate?
In .NET, a delegate is a type that represents a reference to a method with a specific parameter list and return type. A delegate can be thought of as a type-safe function pointer or a callback function. It is a way to pass methods as parameters to other methods, which allows for greater flexibility and modularity in software design.
Delegates can be used to implement the observer pattern, which is a design pattern commonly used in event-driven programming. When an event occurs, an event delegate is invoked to call the methods subscribed to the event, which can then perform their respective actions.
Here is an example of defining and using a delegate in C#:
public delegate void MyDelegate(string message); public class MyClass { public void SayHello(string name) { Console.WriteLine($"Hello, {name}!"); } } public static void Main() { MyClass obj = new MyClass(); MyDelegate del = new MyDelegate(obj.SayHello); del("John"); }
In .NET, a delegate is a type that represents a reference to a method with a specific parameter list and return type. A delegate can be thought of as a type-safe function pointer or a callback function. It is a way to pass methods as parameters to other methods, which allows for greater flexibility and modularity in software design.
Delegates can be used to implement the observer pattern, which is a design pattern commonly used in event-driven programming. When an event occurs, an event delegate is invoked to call the methods subscribed to the event, which can then perform their respective actions.
Here is an example of defining and using a delegate in C#:
public delegate void MyDelegate(string message); public class MyClass { public void SayHello(string name) { Console.WriteLine($"Hello, {name}!"); } } public static void Main() { MyClass obj = new MyClass(); MyDelegate del = new MyDelegate(obj.SayHello); del("John"); }
In this example, a delegate MyDelegate
is defined that takes a string parameter and returns void. A class MyClass
is also defined with a method SayHello
that takes a string parameter and writes a greeting to the console.
In the Main
method, an instance of MyClass
is created, and a delegate del
is instantiated with a reference to the SayHello
method of the MyClass
instance. The delegate is then invoked with the argument “John”, causing the “Hello, John!” message to be printed to the console.
Easy to become expert by Mastering C# String Now
Entity Framework interview questions
14. What is Entity Framework?
Entity Framework (EF) is an Object-Relational Mapping (ORM) framework developed by Microsoft for .NET applications. It allows developers to work with relational databases using domain-specific objects. That eliminates the need to write low-level database access code.
Entity Framework simplifies the data access layer by providing a set of tools and a runtime environment. That enables developers to create, read, update, and delete data from databases using .NET objects.
EF supports a variety of database management systems. Like Microsoft SQL Server, Oracle, MySQL, PostgreSQL, and SQLite. It uses the concept of ORM to map database tables to objects and vice versa.
Entity Framework offers several benefits for .NET developers, including:
- Increased productivity and reduced development time
- Automatic generation of SQL queries based on LINQ expressions
- Enhanced performance with features such as lazy loading, caching, and connection pooling
- Better code maintainability and reduced complexity with a clean separation of concerns between data access and business logic
- Improved data consistency and integrity with features such as transaction management and concurrency control.
15. What is the difference between Entity Framework and ADO.NET?
Entity Framework | ADO.NET |
---|---|
Object-relational mapping (ORM) tool | Data access framework |
Supports LINQ for querying data | Uses SQL for querying data |
Uses DbContext and DbSet classes for accessing data | Uses DataAdapter and DataSet classes for accessing data |
Provides a higher level of abstraction from the underlying database | Provides a lower level of abstraction from the underlying database |
Automatically generates SQL queries | Requires developers to write their own SQL queries |
Provides support for caching data and tracking changes to data | Does not provide built-in support for caching data and tracking changes to data |
Supports lazy loading of related entities | Does not support lazy loading of related entities |
Supports database-independent programming | Requires developers to write code specific to a particular database |
Provides support for automatic creation of database tables | Requires developers to manually create database tables |
Offers better support for managing complex relationships between entities | Offers less support for managing complex relationships between entities |
Suitable for rapid development and prototyping | Suitable for performance-critical applications |
Note: This table provides a general overview of the differences between Entity Framework and ADO.NET, and there may be exceptions or additional details depending on the specific use case.
16. What is DbContext in Entity Framework?
DbContext is a class that acts as a bridge between the domain or entity classes in an application and the database tables.
The DbContext class provides an abstraction layer between the application and the database. It serves as an ORM that translates the objects in the application to database entities and vice versa.
Some of the main responsibilities of the DbContext class are:
- Managing the connection to the database.
- Tracking changes made to the domain classes and synchronizing them with the database.
- Defining the relationships between the domain classes and generating the corresponding database schema.
- Configuring the behavior of Entity Framework, such as lazy loading, change tracking, etc.
17. What is DbSet in Entity Framework?
DbSet represents a collection of entities or database records in a context. It is a property of the DbContext class that allows developers to interact with the database records.
DbSet is also responsible for tracking the changes made to the entities and synchronizing them with the database. When changes are made to an entity in a DbSet
, the DbContext
tracks these changes and persists them to the database when SaveChanges
method is called.
18. What is an entity in Entity Framework?
The entity is a class that represents a table or view in a database. It is a collection of properties that define the data fields in the table or view. Along with their data types, constraints, and relationships with other entities.
19. What is lazy loading in Entity Framework?
Lazy loading is a technique used to delay the loading of related data until it is explicitly requested. By default, when you query an entity that has a navigation property, EF loads the main entity and all its related entities (i.e., eager loading). This can lead to performance issues if the related data is large or if you don’t need all the related data.
With lazy loading, the related entities are not loaded when the main entity is loaded. But only when they are accessed or requested. This can improve the performance of the application. By reducing the amount of data that needs to be fetched from the database.
Lazy loading is enabled by default in Entity Framework 6 and earlier versions.
20. What is eager loading in Entity Framework?
Eager loading is a technique used to load related data of an entity along with the main entity in a single database query.
In Entity Framework, you can use the Include method to perform eager loading. The Include method is used to specify the related entities that you want to load eagerly.
For example, let’s consider the following code that retrieves a Customer entity along with its related Orders entities:
var customer = dbContext.Customers .Include(c => c.Orders) .FirstOrDefault(c => c.CustomerId == customerId);
Eager loading can help to reduce the number of database queries that are required to retrieve data. Which can improve the performance of your application. However, it is important to be aware that eager loading can also result in loading more data than is actually needed. Which can negatively impact performance.
21. What is Code First in Entity Framework?
Code First is a development approach in Entity Framework. That enables developers to write .NET classes (entities) first and then generate a database schema from those classes.
With Code First, developers can define the entities, their properties, and relationships in plain C# classes. Then use a set of conventions or explicit configurations to map them to database tables and columns.
Code First allows developers to work in a domain-driven development style. Where the entities and their relationships are the main focus, and the database schema is generated automatically. This approach can save time and effort in database development and maintenance.
Example, Let’s say we want to create a database to store information about books. First, we create a Book class with properties like Title, Author, and PublicationDate:
public class Book { public int BookId { get; set; } public string Title { get; set; } public string Author { get; set; } public DateTime PublicationDate { get; set; } }
Next, we create a DbContext class called BookContext:
public class BookContext : DbContext { public DbSet<Book> Books { get; set; } }
Run the the following commands in the Package Manager Console:
Add-Migration InitialCreate Update-Database
Then, we can use the following code to add a new book to the database:
using (var db = new BookContext()) { var book = new Book { Title = "Rich Dad Poor Dad", Author = "Robert Kiyosaki and Sharon Lechter", PublicationDate = new DateTime(1997, 4, 8) }; db.Books.Add(book); db.SaveChanges(); }
This will create a new record in the “Books” table with the specified Title, Author, and PublicationDate values.
22. What is Database First in Entity Framework?
Database First is one of the approaches in Entity Framework to create models from an existing database. It allows developers to create an Entity Data Model (EDM) based on an existing database schema. It is the opposite of the Code First approach where we first create domain classes and later map them to the database.
23. What are the different types of relationships supported by Entity Framework?
Entity Framework supports the following types of relationships between entities:
- One-to-One (1:1): Each entity instance on one side has only one related entity instance on the other side, and vice versa.
- One-to-Many (1:N): An entity instance on one side can be related to many instances on the other side. But each instance on the other side is related to only one instance on the first side.
- Many-to-One (N:1): An entity instance on one side is related to only one instance on the other side. But an instance on the other side can be related to many instances on the first side.
- Many-to-Many (N:N): Each instance on both sides can be related to many instances on the other side. This relationship requires a junction table to hold the relationship information.
OOPS Interview Questions
24. What is a class and object?
Class is a blueprint or a template that defines the characteristics and behavior of a particular type of object. It provides a way to organize and encapsulate related data and functions into a single unit, which can then be instantiated to create individual objects.
Object is an instance of a class. When an object is created from a class, it is said to be an instance of that class. Each instance has its own set of data and can be manipulated independently from other instances of the same class. However, all instances of the same class share the same set of methods.
Difference between a class and an object, consider the following example:
public class Person { private string name; private int age; public Person(string name, int age) { this.name = name; this.age = age; } public void SayHello() { Console.WriteLine("Hello, my name is " + this.name + " and I am " + this.age + " years old."); } } Person person1 = new Person("John", 30); Person person2 = new Person("Jane", 25); person1.SayHello(); // outputs "Hello, my name is John and I am 30 years old." person2.SayHello(); // outputs "Hello, my name is Jane and I am 25 years old."
In this example, we have defined a Person
class with member variables name
and age
, and a member function SayHello
. We then create two instances of the Person
class, person1
and person2
, by calling the Person
constructor with different values for name
and age
. Finally, we call the SayHello
method on each instance to print out a greeting.
In this example, Person
is the class, and person1
and person2
are objects (or instances) of the class. The SayHello
method is defined in the class, but can be called on each object independently to produce different output.
25. What is a constructor and what is its purpose?
Constructor is a special method that is called automatically when an instance of a class is created. It has the same name as the class and is used to initialize the object’s properties or perform any other necessary setup.
The purpose of a constructor is to ensure that an object is properly initialized before it is used. It is used to set default values for fields, allocate memory, or initialize other objects that the class depends on.
26. What is object-oriented programming(OOP)?
Object-oriented programming (OOP) is a programming paradigm that focuses on the use of objects and classes to organize and structure code. It is a way of designing and writing software in which data and behavior are combined into reusable building blocks called objects.
OOP provides a number of benefits over other programming paradigms, including:
- Reusability: Objects can be reused in different parts of an application, which reduces code duplication and improves maintainability.
- Modularity: Objects can be developed and tested independently of one another, which makes code easier to manage and modify.
- Extensibility: Objects can be extended to add new functionality without modifying existing code.
- Encapsulation: Data and behavior are encapsulated within objects, which prevents unwanted access and modification of data.
- Polymorphism: Objects can be used interchangeably, which allows developers to write more flexible and reusable code.
27. What are the four main pillars of OOP?
The four main pillars of Object-Oriented Programming (OOP) are:
- Abstraction: It is a fundamental concept in OOP that allows developers to create complex systems by breaking them down into smaller, more manageable parts. It involves hiding unnecessary implementation details from the user and focusing on the essential features and behaviors of an object. In simpler terms, abstraction is the process of identifying essential features and ignoring non-essential details.
- Encapsulation: It is the process of hiding the internal details of an object and providing a public interface through which other objects can interact with it. This can be achieved by creating classes that have private data members and public methods to access and modify those data members. Encapsulation helps to improve the security, maintainability, and flexibility of an object-oriented system.
- Inheritance: It is a fundamental concept of OOP that allows a new class to be based on an existing class. The new class inherits all the properties and behaviors of the existing class and can also add its own features. We can achieve code reusability by using inheritance.
- Polymorphism: The ability of objects to take on multiple forms depending on the context in which they are used. It allows objects of different classes to be treated as if they are objects of the same class, making code more flexible and adaptable.
28. What is abstraction in OOP?
Abstraction is a fundamental concept in OOP that allows developers to create complex systems by breaking them down into smaller, more manageable parts. It involves hiding unnecessary implementation details from the user and focusing on the essential features and behaviors of an object. In simpler terms, abstraction is the process of identifying essential features and ignoring non-essential details.
Abstraction is implemented using abstract classes and interfaces. An abstract class is a class that cannot be instantiated and is used as a base class for other classes. It contains one or more abstract methods, which do not have an implementation in the abstract class and must be implemented in the derived classes. An interface is a contract that defines a set of methods that must be implemented by any class that implements the interface.
Example: Let’s take an example of a car. A car is an abstract concept that can have different types and models such as sedan, SUV, sports car, etc. All these types of cars have some common properties and behaviors such as they have an engine, wheels, brakes, can move forward and backward, etc. We can create an abstract class called “Car” that contains the essential properties and behaviors of a car. The derived classes such as “Sedan”, “SUV”, “SportsCar”, etc. can inherit from the Car class and add their own properties and behaviors.
+---------------------+ | Car | +---------------------+ | - engine | | - wheels | | - brakes | +---------------------+ | + moveForward() | | + moveBackward() | +---------------------+ ^ | +---------------------+ | Sedan | +---------------------+ | + numberOfDoors | +---------------------+ ^ | +---------------------+ | SUV | +---------------------+ | + cargoCapacity | +---------------------+
In the above diagram, we have an abstract class “Car” that contains the essential properties and behaviors of a car such as engine, wheels, brakes, moveForward(), and moveBackward(). The “Sedan” and “SUV” classes inherit from the “Car” class and add their own properties and behaviors. For example, the “Sedan” class adds the “numberOfDoors” property, while the “SUV” class adds the “cargoCapacity” property.
29. What is encapsulation in OOP?
Encapsulation: It is the process of hiding the internal details of an object and providing a public interface through which other objects can interact with it. This can be achieved by creating classes that have private data members and public methods to access and modify those data members. Encapsulation helps to improve the security, maintainability, and flexibility of an object-oriented system.
Encapsulation can be achieved through the use of access modifiers. Like public, private, protected, and internal to control the visibility of a class’s fields, properties, methods, and events. By default, fields and methods are private and can only be accessed within the same class. Properties, on the other hand, can be marked as public or protected to allow other objects to access or modify the underlying fields.
public class BankAccount { private string accountNumber; private decimal balance; public BankAccount(string accountNumber, decimal balance) { this.accountNumber = accountNumber; this.balance = balance; } public void Deposit(decimal amount) { balance += amount; } public void Withdraw(decimal amount) { if (amount > balance) { throw new InvalidOperationException("Insufficient funds."); } balance -= amount; } public decimal GetBalance() { return balance; } }
In this example, the BankAccount
class encapsulates the internal state of a bank account, which includes an account number and a balance. The Deposit
and Withdraw
methods modify the balance, while the GetBalance
method returns the current balance. The account number is not exposed to other objects, as it is marked as private.
_________________________________________________________ | BankAccount | |_________________________________________________________| | - accountNumber: string | | - balance: decimal | |_________________________________________________________| | + BankAccount(accountNumber: string, balance: decimal) | | + Deposit(amount: decimal): void | | + Withdraw(amount: decimal): void | | + GetBalance(): decimal | |_________________________________________________________|
As shown in the diagram, the internal state of the BankAccount
class is hidden from other objects, and only the public methods that modify or retrieve the balance are exposed. This allows for better maintainability and reduces the risk of unintended changes to the account number or balance.
30. What is inheritance in OOP?
Inheritance is a fundamental concept of OOP that allows a new class to be based on an existing class. The new class inherits all the properties and behaviors of the existing class and can also add its own features. We can achieve code reusability by using inheritance.
It is useful because it allows you to define a new class based on an existing class, without having to redefine all of its properties and methods. The derived class can add its own properties and methods, or override those of the base class.
// Base class public class Animal { public void Eat() { Console.WriteLine("The animal is eating."); } } // Derived class public class Dog : Animal { public void Bark() { Console.WriteLine("The dog is barking."); } } // Usage Dog myDog = new Dog(); myDog.Eat(); // inherited method myDog.Bark(); // derived method
+--------+ | Animal | +--------+ ^ | +--------+ | Dog | +--------+
In this diagram, the arrow pointing from Dog
to Animal
represents the inheritance relationship. Dog
is a derived class that inherits from Animal
, which is the base class.
31. What is polymorphism in OOP?
The ability of objects to take on multiple forms depending on the context in which they are used. It allows objects of different classes to be treated as if they are objects of the same class, making code more flexible and adaptable.
Method overloading:
Method overloading is when multiple methods in a class have the same name but different parameters. The appropriate method to call is determined at compile-time based on the parameters passed.
public class MathOperations { public int Add(int x, int y) { return x + y; } public int Add(int x, int y, int z) { return x + y + z; } }
Here, we have two methods named Add
that take different numbers of parameters. We can call these methods like so:
MathOperations math = new MathOperations(); int result1 = math.Add(1, 2); // result1 = 3 int result2 = math.Add(1, 2, 3); // result2 = 6
Method overriding:
Method overriding is when a subclass provides a different implementation of a method that is already defined in its superclass. This allows us to create more specific behavior for a subclass while still using the methods and properties of its parent class.
public class Animal { public virtual void MakeSound() { Console.WriteLine("The animal makes a sound"); } } public class Dog : Animal { public override void MakeSound() { Console.WriteLine("The dog barks"); } } public class Cat : Animal { public override void MakeSound() { Console.WriteLine("The cat meows"); } }
Here, we have a base class Animal
with a virtual method MakeSound
. We then create two subclasses, Dog
and Cat
, which override the MakeSound
method to provide their own implementation.
We can then create instances of these classes and call their MakeSound
methods:
Animal animal1 = new Dog(); Animal animal2 = new Cat(); animal1.MakeSound(); // outputs "The dog barks" animal2.MakeSound(); // outputs "The cat meows"
This demonstrates polymorphism because we are able to call the same method (MakeSound
) on different objects and get different behavior depending on the object’s actual type.
32. What is the difference between an abstract class and an interface?
Here are the difference between an abstract class and an interface:
Abstract Class | Interface |
---|---|
An abstract class can have both abstract and non-abstract methods. | An interface can only have abstract methods, properties, and events. |
An abstract class can have access modifiers. | All members of an interface are public by default. |
An abstract class cannot support multiple inheritance | An interface can support multiple inheritance |
An abstract class can provide implementation for some methods. | An interface cannot provide implementation for any of its members. |
An abstract class can contain constructors. | An interface cannot contain constructors. |
An abstract class can have fields and constants. | An interface cannot have fields or constants. |
An abstract class can define properties. | An interface can define properties but cannot implement them. |
An abstract class can be inherited by a concrete class. | A class can implement multiple interfaces. |
An abstract class is used when there is a common implementation among the classes. | An interface is used when there is no common implementation among the classes, but they need to have a certain behavior. |
An abstract class is relatively less flexible, as it cannot be changed once it is defined. | An interface is relatively more flexible, as it can be added or removed from a class without changing its internal implementation. |
33. What is a static class?
A static class is a special type of class that cannot be instantiated. It can only contain static members, i.e., members that are associated with the class itself, rather than with instances of the class. Static classes are typically used to provide utility functions that are not specific to any particular instance of a class. Which can be called directly without creating an instance of the class.
Some key characteristics of static classes include:
- They cannot be instantiated, i.e., you cannot create an object of a static class using the new keyword.
- They can only contain static members, including fields, methods, and properties.
- They are implicitly sealed, i.e., you cannot inherit from a static class.
- They are typically used to provide utility functions or services that are not specific to any particular instance of a class.
public static class MathUtils { public static int Add(int x, int y) { return x + y; } public static int Multiply(int x, int y) { return x * y; } }
In this example, MathUtils
is a static class that provides two static methods, Add
and Multiply
, which can be called directly using the class name, without creating an instance of the class:
int sum = MathUtils.Add(2, 3); // returns 5 int product = MathUtils.Multiply(2, 3); // returns 6
34. What is a sealed class?
A sealed class is a class that cannot be inherited by any other class. It is a way of restricting the inheritance hierarchy for a particular class.
When a class is marked as sealed, it cannot be used as a base class for any other class. This means that other classes cannot derive from a sealed class, and they cannot be extended or modified further.
Here are some key points to keep in mind about sealed classes:
- A sealed class can still inherit from other classes, but it cannot be inherited by any other class.
- The sealed keyword is used to prevent the inheritance of a class.
- sealed classes can be used to provide a fixed implementation of a class that is not meant to be extended or modified.
- sealed classes can be useful for security purposes since they limit the potential for malicious code to inherit and modify the behavior of the class.
sealed class MySealedClass { // Class implementation }
In this example, the MySealedClass
class is marked as sealed
, which means that it cannot be inherited by any other class.
35. What is a partial class?
A partial class allows you to split a class definition into multiple files. You can declare different parts of the class in different files, and the C# compiler will combine them into a single class at compile time. This can be useful for organizing large classes or for separating autogenerated code from user-written code.
Partial classes must be in the same namespace and assembly, and they must have the same access modifier. They also cannot contain multiple definitions of the same member, but they can extend each other using inheritance.
// MyClass.cs public partial class MyClass { public void Method1() { /* ... */ } } // MyClass.Generated.cs public partial class MyClass { public void Method2() { /* ... */ } }
In this example, MyClass
is split across two files, and each file declares a partial class with the same name. The class has two methods, Method1
and Method2
, declared in different files. At compile time, the C# compiler will merge the two files into a single MyClass
class with both methods.
36. What is a abstract class?
An abstract class is a class that cannot be instantiated on its own but can only be used as a base class for other classes. It contains one or more abstract methods, which are defined but not implemented in the abstract class. The implementation of these abstract methods is provided by the derived classes.
An abstract class can also contain non-abstract methods and properties that have a default implementation. However, any class that derives from an abstract class must provide an implementation for all abstract methods inherited from the abstract class.
The main purpose of an abstract class is to provide a common interface or contract for its derived classes. This enables the derived classes to share a common behavior or functionality while still having the flexibility to implement their own specific behavior.
public abstract class Animal { public string Name { get; set; } public abstract void MakeSound(); } public class Dog : Animal { public override void MakeSound() { Console.WriteLine("Woof!"); } } public class Cat : Animal { public override void MakeSound() { Console.WriteLine("Meow!"); } }
In this example, Animal
is an abstract class that defines a property Name
and an abstract method MakeSound()
. The Dog
and Cat
classes derive from the Animal
class and provide an implementation for the MakeSound()
method.
.NET Core Interview Questions
37. What is the difference between .NET Framework and .NET Core?
Here is the key differences between .NET Framework and .NET Core:
Feature | .NET Framework | .NET Core |
---|---|---|
Cross-platform | No, runs only on Windows | Yes, runs on Windows, macOS, Linux |
Deployment | Installed with OS | Self-contained or installed via runtime |
Application type | Windows desktop, web, and mobile | Web, desktop, and mobile |
Runtime size | Large (200 MB – 1 GB) | Small (10 MB – 200 MB) |
Performance | Good for Windows applications | Good for web and cloud applications |
Development | Visual Studio | Visual Studio, VS Code, and others |
Support | Mature and well-established | Evolving and growing |
Open source | No | Yes |
38. What is middleware in ASP.NET Core?
Middleware is software components that are used to handle requests and responses in the request pipeline. The middleware pipeline is a series of components that execute in a specific order to handle each request and response.
Each middleware component has access to the request and response as they flow through the pipeline. Middleware can modify the request or response, or it can simply log information about the request and response.
ASP.NET Core provides a set of built-in middleware components that can be used to perform common tasks such as authentication, caching, routing, logging, and exception handling. Developers can also create their own custom middleware components to handle specific tasks.
The middleware pipeline is configured in the Startup.cs
or Program.cs
file of an ASP.NET Core application. Each middleware component is added to the pipeline using the app.Use()
method. The order in which middleware components are added to the pipeline is important, as each component will execute in the order it was added.
39. What is dependency injection in ASP.NET Core?
Dependency injection (DI) is a design pattern and technique used to manage the dependencies of an application. By providing objects (dependencies) to a class rather than having the class create the objects itself.
DI is used to provide objects to controllers, services, and other components of an application. This helps to decouple the application components and makes the code more modular and testable.
With DI, dependencies are defined as services, which are registered with the built-in service container. The service container is responsible for creating and managing the lifecycle of services, and it resolves dependencies by providing the required objects to the classes that need them.
ASP.NET Core includes a built-in DI system that makes it easy to implement DI in an application. Developers can use the built-in service container or replace it with a third-party container.
To use DI in ASP.NET Core, developers must define services by registering them with the service container in the Startup.cs
or Program.cs
file. Once registered, the services can be injected into controllers, services, and other components by specifying them as parameters in the constructor or using property injection.
40. How do you configure services in ASP.NET Core?
Services are configured in the Startup.cs or Program.cs file of an application. To configure services, the ConfigureServices method is used, which is called during application startup.
To configure a service, developers must first register it with the built-in service container. This is typically done using the services.Add<service>()
method, where <service>
is the type of the service being registered.
For example, to register a service that provides data access, the following code can be used:
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
This code registers the MyDbContext service, which is used to interact with a database, and configures it to use a SQL Server database connection.
In addition to registering services, developers can also configure options for the services by chaining configuration methods onto the service registration.
services.AddScoped<IMyService, MyService>();
ASP.NET Core also includes a number of built-in services that can be configured using the services.Add<service>()
method. These services include authentication, caching, routing, logging, and more.
41. What is the difference between the AddSingleton, AddScoped, and AddTransient methods when registering services in .NET Core?
The AddSingleton
, AddScoped
, and AddTransient
methods are used to register services with the dependency injection container.
AddSingleton
: This method registers a single instance of a service with the container. The same instance is returned every time the service is requested. This is useful for services that are expensive to create or that need to maintain state across the application.AddScoped
: This method registers a service with the container with a scoped lifetime. A new instance of the service is created once per scope (e.g., a request in an ASP.NET Core application), and that same instance is returned each time the service is requested within that scope. This is useful for services that are lightweight and don’t need to maintain state across the application.AddTransient
: This method registers a service with the container with a transient lifetime. A new instance of the service is created each time it is requested. This is useful for lightweight services that don’t maintain any state and are inexpensive to create.
In general, you should use the most appropriate lifetime for the service you’re registering. If the service needs to maintain state or is expensive to create, use AddSingleton
. If the service is lightweight and doesn’t maintain state, use AddTransient
. If the service needs to maintain state across a single request or operation, use AddScoped
.
42. What is Entity Framework Core?
Entity Framework Core (EF Core) is an open-source, cross-platform Object-Relational Mapping (ORM) framework for .NET Core.
It provides a set of tools and libraries that developers can use to interact with relational databases using OOP techniques.
EF Core is designed to simplify the process of working with databases by providing a higher level of abstraction over the database schema. With EF Core, developers can define data models using classes and properties, and EF Core automatically creates the database schema and performs the necessary database operations.
EF Core supports a wide range of database providers, including SQL Server, MySQL, PostgreSQL, SQLite, and more. It also supports a variety of database operations, including querying data, inserting, updating, and deleting records.
Some of the key features of EF Core include:
- Support for database providers and databases.
- Support for LINQ queries, which allows developers to query data using C# or Visual Basic syntax.
- Automatic schema generation and migrations.
- Change tracking, which allows EF Core to track changes to entities and update the database accordingly.
- Support for transactions and concurrency.
- Built-in support for unit testing.
Overall, EF Core is a powerful and flexible ORM framework that makes it easy for developers to work with relational databases.
43. What is the difference between a DbSet and a DbContext in Entity Framework Core?
In Entity Framework Core, a DbSet and a DbContext are two important classes that are used to work with relational databases.
A DbSet represents a collection of entities in the database. It is typically used to perform CRUD (Create, Read, Update, Delete) operations on a specific entity type.
For example, if an application has a database table for products, a DbSet<Product> can be used to perform database operations on the Product entity.
A DbContext, on the other hand, is a class that represents a database session and provides a way to interact with the database using DbSet. It is responsible for managing the database connection and transaction, as well as tracking changes made to entities.
public class MyDbContext : DbContext { public DbSet<Product> Products { get; set; } }
44. What is the role of the OnModelCreating method in Entity Framework Core?
The OnModelCreating
method in Entity Framework Core is used to configure the model that represents the database schema for the application. This method is typically overridden in the application’s DbContext
class and is called by EF Core when the context is being initialized.
The OnModelCreating
method allows developers to define various aspects of the database schema, such as entity mappings, relationships, indexes, and constraints.
Here is an example of using the OnModelCreating
method to configure the model for a simple blogging application:
using Microsoft.EntityFrameworkCore; public class BloggingContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Integrated Security=True"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .HasKey(b => b.BlogId); modelBuilder.Entity<Blog>() .Property(b => b.Url) .IsRequired(); modelBuilder.Entity<Post>() .HasKey(p => p.PostId); modelBuilder.Entity<Post>() .Property(p => p.Title) .HasMaxLength(200); modelBuilder.Entity<Post>() .HasOne(p => p.Blog) .WithMany(b => b.Posts) .HasForeignKey(p => p.BlogId); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public ICollection<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } }
45. How do you query a database using Entity Framework Core?
You can query a database using Entity Framework Core by writing LINQ (Language Integrated Query) queries against your DbContext
.
Here are some examples of querying the database using Entity Framework Core:
using (var context = new BloggingContext()) { // Query for all blogs var allBlogs = context.Blogs.ToList(); // Query for a specific blog by ID var blog = context.Blogs.FirstOrDefault(b => b.BlogId == 1); // Query for all posts associated with a blog var blogPosts = context.Posts.Where(p => p.BlogId == blog.BlogId).ToList(); // Query for all blogs ordered by URL in ascending order var orderedBlogs = context.Blogs.OrderBy(b => b.Url).ToList(); }
46. What is the difference between synchronous and asynchronous programming in .NET Core?
Synchronous programming is the traditional way of writing code. Where a method call blocks the current thread until the method completes and returns a result. This means that the thread is unavailable for other work until the method call is complete.
Synchronous programming can be simple and easy to understand, but it can also lead to performance issues when working with long-running or I/O-bound operations.
public void DownloadFile(string url, string filePath) { WebClient client = new WebClient(); client.DownloadFile(url, filePath); }
Asynchronous programming allows a method to execute without blocking the current thread. Instead of waiting for a method to complete, the current thread can continue executing other work, while the asynchronous method runs in the background. When the asynchronous method completes, it signals the caller, typically through a Task object, and returns the result.
Asynchronous programming can improve the responsiveness and scalability of applications, especially when working with long-running or I/O-bound operations, such as network requests or file operations. It can also make better use of available resources, by allowing multiple tasks to execute concurrently on a single thread.
To support asynchronous programming, .NET Core includes a number of asynchronous programming features, including the async
and await
keywords, which allow developers to write asynchronous code that looks similar to synchronous code. .NET Core also includes a variety of asynchronous APIs, such as the Task and Task<T>
classes, which make it easy to work with asynchronous operations.
public async Task DownloadFileAsync(string url, string filePath) { WebClient client = new WebClient(); await client.DownloadFileTaskAsync(url, filePath); }
47. What is a LINQ query in C#?
LINQ (Language-Integrated Query) is a feature in C# that provides a simple and efficient way to query data from different data sources like arrays, collections, databases, and XML documents.
In C#, LINQ queries are written using a syntax similar to SQL (Structured Query Language). A LINQ query begins with a from
clause, followed by an optional where
clause, and then one or more additional clauses (such as select
, group by
, orderby
, join
, etc.) to refine the query.
Here’s an example of a LINQ query that retrieves all the strings in an array that start with the letter “A”:
string[] fruits = { "Apple", "Banana", "Apricot", "Pear", "Avocado" }; var query = from fruit in fruits where fruit.StartsWith("A") select fruit; foreach (var fruit in query) { Console.WriteLine(fruit); }
In this example, the from
clause specifies the data source (fruits
), and the where
clause filters the data to include only the strings that start with the letter “A”. The select
clause specifies the data to be retrieved, which in this case is the entire fruit string. The query
variable holds the results of the query, which are then displayed using a foreach
loop.
LINQ queries can be used with many different data sources and can be very powerful when used correctly.
48. What is serialization?
Serialization is the process of converting an object into a format that can be stored or transmitted across a network.
.NET Core provides several serialization options, including XML serialization, JSON serialization, and binary serialization. Each of these options has its own advantages and disadvantages, depending on the specific requirements of the application.
Here’s an example of using the JsonSerializer class to serialize an object to JSON:
using System; using System.Text.Json; class Program { static void Main(string[] args) { Person person = new Person { Name = "John Doe", Age = 42 }; string json = JsonSerializer.Serialize(person); Console.WriteLine(json); } } class Person { public string Name { get; set; } public int Age { get; set; } }
49. What is deserialization?
Deserialization is the process of converting serialized data, such as JSON or XML, back into an object or data structure in memory.
Here’s an example of using the JsonSerializer class to deserialize JSON data into an object:
using System; using System.Text.Json; class Program { static void Main(string[] args) { string json = @"{""Name"":""John Doe"",""Age"":42}"; Person person = JsonSerializer.Deserialize<Person>(json); Console.WriteLine(person.Name); Console.WriteLine(person.Age); } } class Person { public string Name { get; set; } public int Age { get; set; } }
50. How to read configuration in .NET Core?
You can read configuration data from various sources, including JSON files, XML files, environment variables, and command-line arguments. The configuration data is stored in a Configuration
object, which is an instance of the IConfiguration
interface.
Here’s an example of how to read configuration data from a JSON file named appsettings.json
:
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; IConfigurationBuilder configBuilder = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); IConfiguration config = configBuilder.Build(); string connectionString = config.GetValue<string>("ConnectionStrings:DefaultConnection");