Interview Notes Merged
Interview Notes Merged
ASP.NET Web Forms is one of Microsoft’s earlier frameworks, introduced in 2002 with
the .NET Framework 1.0. It is designed for building dynamic, data-driven web applications using a
drag-and-drop, event-driven programming model similar to Windows Forms.
Current Status: ASP.NET Web Forms is considered legacy technology and is no longer actively
developed. For new projects, Microsoft recommends using ASP.NET Core.
ASP.NET MVC:
Current Status: While ASP.NET MVC is still supported, Microsoft has shifted its focus to ASP.NET
Core MVC, which offers cross-platform capabilities and enhanced performance. For new projects,
ASP.NET Core MVC is recommended.
ASP.NET Web API is a framework for building HTTP-based services that can be consumed by various
clients, including browsers, mobile devices, and desktop applications. These HTTP services can
return data in various formats, including JSON and XML. ASP.NET Web API was released in 2012 as
part of the .NET framework 4. So, ASP.NET Web API is a framework introduced to build RESTful HTTP
services, enabling communication between clients (like browsers or mobile apps) and servers using
HTTP.
Note: ASP.NET Web API has been unified into ASP.NET Core as part of ASP.NET Core Web API. For
new projects, using ASP.NET Core Web API is recommended to take advantage of cross-platform
support and improved performance.
ASP.NET Core MVC is a cross-platform, open-source framework for building modern, cloud-
optimized, and high-performance applications following the Model-View-Controller (MVC) design
pattern. It is part of ASP.NET Core, which was first released in 2016 as a complete rewrite of ASP.NET
to support cross-platform development and improved performance.
Note: ASP.NET Core MVC is actively developed and is the recommended framework for new web
application projects. It represents the future direction of Microsoft’s web development stack.
ASP.NET Core Web API is a framework for building HTTP-based services in ASP.NET Core, designed
for cross-platform and high performance. It is best suited for building RESTful services with high
performance and cross-platform capabilities.
Note: ASP.NET Core Web API is actively maintained and recommended for building modern,
scalable, and high-performance APIs. It benefits from the ongoing enhancements in the ASP.NET
Core ecosystem.
ASP.NET Core Razor Pages:
ASP.NET Core Razor Pages is a page-based programming model introduced in ASP.NET Core 2.0
(2017). It simplifies web application development by enabling a page-focused approach, where each
page handles its own actions and view logic. Unlike MVC, Razor Pages focuses on individual pages,
making it easier to build simple web applications.
Note: ASP.NET Core Razor Pages is actively developed and widely adopted for scenarios where a
page-based architecture is beneficial.
ASP.NET Core Blazor is a modern framework introduced with .NET Core 3.0 in 2019 that allows
developers to build interactive web applications using C# instead of JavaScript. It is ideal for .NET
developers looking to build interactive client-side Web UIs with .NET without relying on JavaScript.
Blazor has two modes of operation:
• Blazor Server: Runs on the server, and updates are sent to the browser via SignalR.
Note: Blazor is actively developed and rapidly gaining popularity as a modern framework for building
interactive web applications. Microsoft continues to invest heavily in Blazor, adding new features
and improving performance. It represents a significant shift towards full-stack .NET development.
Understanding how these frameworks interrelate can help in making informed decisions about
technology stacks and migration strategies:
• Legacy to Modern: Projects using ASP.NET Web Forms can consider migrating to ASP.NET
Core MVC or Razor Pages for better performance, maintainability, and cross-platform
support.
• NET Core MVC vs. Razor Pages: Both ASP.NET Core MVC and Razor Pages are part of the
ASP.NET Core ecosystem. ASP.NET Core MVC is preferred for applications requiring complex
routing and controller logic, while ASP.NET Core Razor Pages are ideal for simpler, page-
focused scenarios.
• Web API Integration: .NET Core MVC and Web API have been unified, allowing seamless
integration of web applications and APIs within the same project.
Selecting the appropriate Microsoft web technology depends on various factors, including project
requirements, team expertise, performance needs, and future scalability:
• New Projects: Prefer NET Core MVC or Razor Pages for traditional web applications, and
Blazor for interactive client-side applications.
• API Development: Use .NET Core Web API to build robust, scalable APIs.
• Legacy Maintenance: Continue maintaining existing ASP.NET Web Forms, ASP.NET MVC, and
ASP.NET Web API applications, but consider planning migrations to modern ASP.NET Core
frameworks.
• Cross-Platform Needs: Use NET Core frameworks to develop and deploy applications on
multiple operating systems.
• Full-Stack .NET Development: Use Blazor to streamline development using C# across both
client and server sides.
HTML pages are generated on the server for each client request. User actions (like clicking a link or
submitting a form) trigger requests to the server, which processes the request and returns a new
HTML page or updates a portion of the page.
Most of the rendering is handled on the client (browser) using JavaScript frameworks. The initial
page load fetches the necessary HTML, CSS, and JavaScript. Subsequent user interactions update the
UI dynamically without full page reloads by communicating with server APIs as needed.
Note: In the context of Microsoft Web Technologies, frameworks like ASP.NET Core MVC and
ASP.NET Core Razor Pages align more closely with traditional web applications, emphasizing server-
side rendering and ease of maintenance. On the other hand, ASP.NET Core Blazor is used to develop
interactive client-side applications, allowing developers to build SPAs using C# instead of JavaScript.
In this article, I will give you a brief introduction to the ASP.NET Core Framework. Nowadays, when
it comes to software development, everyone is talking about Free, Open-Source, and Cross-
Platform Development. As we all know, Microsoft is well known for its Windows-based products.
Now, we are in a new age of software development. For this, Microsoft introduced a new
revolutionary product, ASP.NET Core or .NET.
For years, ASP.NET was the go-to framework for building data-driven web applications. Since then,
the ASP.NET Framework has undergone steady evolutionary change, and finally, the most decent
evolution is ASP.NET Core (you can also call it .NET).
However, ASP.NET Core is not a continuation of the ASP.NET Framework but rather a complete
redesign. It represents a significant shift, introducing a more modular, cross-platform framework
that can be used to build modern, cloud-based applications.
• ASP.NET Core is not just a continuation of ASP.NET but rather a completely new framework.
It’s a rewrite with a more modular design and support for cross-platform development.
• It retains some familiar concepts but introduces fundamental changes, especially in its
handling of performance, deployment, and modularity.
What is ASP.NET Core?
• ASP.NET Core is the modern, high-performance web development framework for .NET, that
runs on Windows, Linux, macOS, and Docker.
• ASP.NET is a popular web development framework for building web apps on the .NET
platform.
• ASP.NET Core is the open-source version of ASP.NET that runs on macOS, Linux, and
Windows. It was first released in 2016 and is a redesign of earlier Windows-only versions of
ASP.NET.
For more information, visit the official ASP.NET Core page: https://dotnet.microsoft.com/en-
us/learn/aspnet/what-is-aspnet-core
Nowadays, the ASP.NET Core framework is becoming more and more popular among developers.
There are a number of reasons why developers are using it, and some of them are listed below:
High Performance:
ASP.NET Core is optimized for high performance. Its modular architecture allows developers to
include only necessary dependencies, resulting in faster and more efficient applications. Benchmarks
demonstrate that applications developed with ASP.NET Core are significantly faster than those built
with previous versions of ASP.NET and are ideal for high-traffic, cloud-native applications. For a
better understanding, please look at the following image, which is provided on the Official Microsoft
Site:
Open Source
ASP.NET Core framework is open-source, which is the main reason for its popularity. The entire
source code for ASP.NET Core Framework is available on GitHub
at https://github.com/dotnet/aspnetcore, and allows developers to:
• Contribute to its development, benefiting from a huge community with over 100,000
contributions from more than 3,700 companies.
All aspects of .NET are open source, including class libraries, runtime, compilers, languages, the
ASP.NET Core web framework, Windows desktop frameworks, the Entity Framework Core data
access library, and more.
The ASP.NET Core team is always there to support your effort in developing the application. It
receives bug fixing and improvement updates on a regular basis, usually within a short time period.
You don’t have to wait longer for updates. For more information, visit the official ASP.NET Core
page: https://dotnet.microsoft.com/en-us/platform/open-source
Cross-Platform:
The ASP.NET Core Framework is designed from scratch to be Cross-Platform, meaning ASP.NET apps
can be developed and run on Windows, Linux, macOS, and Docker. This means we can build
applications that run across different operating systems without needing to build different
applications for different platforms using different frameworks.
Compared with Traditional ASP.NET Framework, earlier versions of ASP.NET Framework applications
can only run on Windows platforms. On the other hand, ASP.NET Core applications can be
developed and run on different platforms, such as Windows, Mac, or Linux operating systems. We
can host the earlier ASP.NET Framework applications only on IIS, whereas we can host the ASP.NET
Core applications on IIS, Nginx, Apache, or within Docker containers.
The framework is built to be modular, which allows developers to include only the necessary
libraries. This reduces the application’s overall size and improves performance. Dependencies are
managed via NuGet packages, making it easy to add or remove features.
ASP.NET Core includes a built-in dependency injection (DI) container. This feature simplifies the
management of service lifetimes and dependencies, leading to more maintainable and testable
code.
Cloud-Ready:
ASP.NET Core is designed for cloud deployment. It provides configuration features that simplify
deploying and scaling applications in cloud environments like Microsoft Azure.
The latest stable version of .NET Core is .NET 8, released in November 2023. Starting with .NET 5, the
term “Core” was removed, and it is now simply called .NET (e.g., .NET 6, .NET 7, .NET 8). Microsoft
releases new major versions every year in November, alternating between Long-Term Support (LTS)
and Short-Term Support (STS) releases:
• Long-Term Support (LTS) Releases: Even-numbered releases (e.g., .NET 6, .NET 8) are
designated as LTS releases. They receive support and patches for three years, making them
ideal for production environments.
• Standard-Term Support (STS) Releases: Odd-numbered releases (e.g., .NET 5, .NET 7)
receive support and patches for 18 months, suitable for projects that can adopt newer
versions more frequently.
Note: Customers can choose Long Term Support (LTS) releases or Standard Term Support (STS)
releases. The quality of all releases is the same. The only difference is the length of support. LTS
releases get free support and patches for 3 years. STS releases get free support and patches for 18
months.
For more information, visit the official ASP.NET Core page: https://dotnet.microsoft.com/en-
us/platform/support/policy/dotnet-core
If you are familiar with ASP.NET, here are some features that are no longer part of ASP.NET Core:
• Global.asax File: This has been replaced by the Program.cs file, which is used to configure
the application’s startup process.
• HTTP Handlers and HTTP Modules: Replaced by Middleware Components in the ASP.NET
Core request pipeline.
The following are the Differences Between .NET Framework and .NET Core
.NET Framework
• Use Cases: Ideal for applications tightly integrated with the Windows ecosystem, such as
desktop applications, or for maintaining large existing applications built on the .NET
Framework.
.NET Core
• Architecture: Modular, allowing developers to include only necessary packages via NuGet,
resulting in lighter and more efficient applications.
• Support and Development: Actively developed with regular additions of new features,
performance improvements, and enhancements.
• Open Source: It is open source and hosted on GitHub with over 100,000 contributions from
more than 3,700 companies.
• Use Cases: Perfect for building modern web applications, microservices, and applications
requiring cross-platform functionality.
Many people are confused between ASP.NET Core and .NET Core. Please note that ASP.NET Core
and .NET Core are not the same. They are different, just like ASP.NET and .NET Framework are
different.
ASP.NET Core is a web framework for building web applications, services, and APIs. .NET Core is the
runtime that supports running ASP.NET Core applications. It is also the foundation for other types of
applications like console, desktop, and mobile apps (through .NET MAUI). So, .NET Core provides the
runtime environment, while ASP.NET Core is the web application framework that runs on it. For a
better understanding, please have a look at the following diagram:
• Install .NET Core Runtime to run applications and install .NET Core SDK to build applications.
ASP.NET Core:
• If you want to develop and run .NET Core Applications, you need to install the .NET Core
SDK, which will automatically install the .NET Runtime. If you only want to run .NET Core
Applications, you only need to install the .NET Core Runtime.
Note: ASP.NET Core does not have a separate versioning system; it is the same as the other .NET
Core versions.
We have some knowledge about the .Net core and .Net framework, so now, let us discuss some key
differences between these platforms. First and foremost, we know .Net core is a free, open-source
development platform designed and developed by Microsoft to develop general-purpose cloud-
based software applications that are cross-platform that can be executed on Mac OS, Windows, and
Linux.
.Net framework is a development platform for coding and executing applications on Windows. This
framework consists of various details such as developer tools, programming languages, and libraries
to design web and desktop apps. It also has a layout of primary requirements for the development of
applications such as Database connectivity, UI, Services, etc. We can say that .Net core is a platform
but not a full-fledged framework. Or, in more simple terms, we can say that .Net Core is just a subset
of .Net Framework. Wherein .Net Core is the most recent version of .Net Framework, an open-
source cross-platform designed for modern apps.
Platform Compatibility:
• .NET Framework: Primarily designed for Windows and runs exclusively on the Windows
operating system.
• .NET Core: Designed for cross-platform development and can run on Windows, macOS, and
Linux.
Open Source:
• .NET Core: Open source, allowing for community contributions and transparency in
development.
Cross-Platform:
• .NET Framework: .Net framework is in harmony with the Windows platform; in spite of the
fact that it was designed and developed for all the other platforms, it Favors Windows!
• .NET Core: .Net Core is based on the principle that says, “Code once, execute anywhere”;
therefore, we can say it is cross-platform. It assists Windows, Mac OS, and Linux platforms.
Since it is compatible with all platforms, you can develop your code on any and run it on any.
• .NET Framework: Monolithic framework where you generally need to install the entire
framework on a system.
• .NET Core: Modular architecture allows you to include only the necessary components,
resulting in smaller deployments and reduced overhead.
Deployment:
• .NET Framework: Applications built on .NET Framework often require the appropriate
version of the framework to be installed on the target machine, leading to larger
deployment packages.
• .NET Core: Applications can be published as self-contained packages with all necessary
dependencies included, making deployment more straightforward.
• .NET Framework: In contrast with the .Net core, the .Net Framework offers relatively slow
performance and scalability.
• .NET Core: It has been seen that the .Net core offers good scalability and performance
compared with the .Net framework for its architecture.
• .NET Framework: Applications run on the Common Language Runtime (CLR) provided by the
framework.
• .NET Core: It also runs on the CLR but with enhancements for performance and cross-
platform support.
• .NET Core: Offers a subset of Windows-specific APIs, with some differences and limitations
due to cross-platform compatibility.
Web Frameworks:
• .NET Framework: Includes technologies like ASP.NET Web Forms, ASP.NET MVC, and Web
API.
• .NET Core: Introduces ASP.NET Core, a unified framework for building web applications and
APIs with enhanced performance and cross-platform capabilities.
• .NET Framework: Limited to a few languages like C# and Visual Basic .NET.
• .NET Core: Offers broader language support, including C#, F#, and Visual Basic .NET.
• .NET Framework: An extensive ecosystem of libraries and third-party components has been
built over the years.
• .NET Core: Some libraries from the .NET Framework may not be directly compatible due to
architectural differences, but efforts have been made to create compatible versions.
• .NET Core: Tends to have better backward compatibility and versioning due to its modular
nature.
Future Direction:
• .NET Framework: Microsoft’s focus has shifted toward .NET Core and its evolution into .NET
5 and beyond.
• .NET Core: Evolved into .NET 5, .NET 6, and future versions, aiming to provide a unified and
modern development platform.
It’s important to verify the current state of .NET technologies and frameworks from official Microsoft
sources or other up-to-date references, as the information provided here might not reflect the latest
developments.
The choice between .NET Core and .NET Framework depends on your specific use case,
requirements, and goals. Both frameworks have their own strengths and considerations. Here are
some factors to consider when deciding between .NET Core and .NET Framework:
2. Modern Development: If you’re looking for a more modern development experience with a
focus on modularity, performance, and lightweight deployments, .NET Core and its
successors are designed with these goals in mind.
5. Legacy Applications: If you have existing applications built on .NET Framework and they are
working well, there might not be an immediate need to migrate. However, consider future
support and compatibility.
6. Library Ecosystem: .NET Framework has a mature library ecosystem developed over many
years. Depending on your application’s requirements, you might find more libraries and
components readily available for .NET Framework.
7. Deployment and Installation: .NET Core (or its successors) allows for more flexible
deployment options, including self-contained deployments, which can simplify distribution
and installation.
8. Open Source and Community: .NET Core’s open-source nature fosters community
contributions, transparency, and faster updates.
9. Future-Proofing: .NET Core (and its successors) is Microsoft’s focus for the future, strongly
emphasizing continuous improvement and cross-platform support.
It’s important to assess your project’s requirements and constraints before deciding. For new
projects, especially those with cross-platform aspirations, .NET Core (or .NET 5 and beyond) might be
a better choice. For existing applications, consider factors like compatibility, available resources, and
the potential benefits of migrating to a more modern framework.
The answer to this query would be NO, as we have discussed earlier. .Net core and .Net framework
both have their upper hand and drawbacks and can be used according to the project’s needs.
But, yes, .NET Core is being positioned as the successor to .NET Framework. Microsoft has been
working on unifying the two frameworks into a single platform called “.NET 5” and subsequent
versions. Here’s the progression of this transition:
• .NET Core: .NET Core was initially introduced as an open-source, cross-platform framework
aimed at modernizing and expanding the capabilities of the .NET ecosystem. It was
developed to address some of the limitations of the traditional .NET Framework, including
cross-platform compatibility, modularity, and performance improvements.
• .NET 5: Microsoft announced that .NET 5 would be the first version of the unified platform,
merging the features and capabilities of both .NET Core and .NET Framework. .NET 5 was
released in November 2020 and marked a significant step in the direction of convergence.
• Subsequent Versions: Following .NET 5, subsequent versions like .NET 6, .NET 7, and so on
continue the evolution of the unified platform. These versions aim to provide a modern,
cross-platform, and streamlined development experience while incorporating .NET Core and
.NET Framework features.
This unification intends to provide developers with a single platform that combines both
frameworks’ best features and capabilities. This unified platform retains the cross-platform
compatibility, performance improvements, and open-source nature of .NET Core while also
incorporating the extensive libraries, APIs, and Windows-specific features of the .NET Framework.
Does .Net Core Have a Future?
Yes, .NET Core has a future and has evolved into the unified .NET platform, including .NET 5, .NET 6,
and subsequent versions. Microsoft’s focus has shifted towards this unified platform, and it is
actively being developed and maintained. Here are some points that highlight the future of .NET
Core and the unified .NET platform:
• Continued Development: Microsoft has been investing significant resources into the
development of the unified .NET platform. New versions, such as .NET 6 and beyond, are
being released with regular updates and improvements.
• Modern Development: The unified .NET platform retains the core principles of .NET Core,
such as cross-platform compatibility, modularity, and performance improvements, making it
a modern and versatile development platform.
• Cross-Platform Support: The unified .NET platform maintains its cross-platform capabilities,
allowing developers to build and run applications on Windows, macOS, and Linux.
• Open Source and Community: The platform remains open source, allowing community
contributions, transparency, and collaboration in its development.
• Tooling and Ecosystem: Microsoft is enhancing the tooling and ecosystem around the
unified .NET platform, including development environments, libraries, and resources for
developers.
• Support and Adoption: Many organizations have already adopted .NET Core for their
projects, and this trend is likely to continue with the unified .NET platform. Microsoft’s
commitment to the platform’s development provides confidence in its longevity.
• Migration Path: Microsoft has provided guidance and tools for migrating applications from
.NET Framework to the unified .NET platform, ensuring that existing investments in .NET
technology can be leveraged in the future.
• Cloud and Web Development: The unified .NET platform, particularly ASP.NET Core, is well-
suited for cloud-native and web application development, which are areas of increasing
importance in modern software development.
Yes, .NET 5 (and its subsequent versions like .NET 6, .NET 7, and beyond) is designed to replace the
traditional .NET Framework. Microsoft’s goal has been to unify the capabilities of .NET Core and .NET
Framework into a single, modern platform. .NET 5 is the first step in this unification process. Here
are some key points to consider:
• Unified Platform: .NET 5 is part of the unified .NET platform that merges the features and
capabilities of both .NET Core and .NET Framework.
• Cross-Platform: Like .NET Core, .NET 5 is cross-platform and can run on Windows, macOS,
and Linux.
• Windows APIs: The unified platform provides access to a subset of Windows APIs, ensuring
that Windows-specific functionality is still available.
• Web Development: ASP.NET Core, which is part of the unified platform, offers modern web
development features and capabilities, making it a suitable replacement for ASP.NET Web
Forms and MVC.
• Open Source and Community: .NET 5 and the unified .NET platform are open source,
fostering community contributions and collaboration.
• Long-Term Support: Certain versions of .NET, such as .NET 6 LTS (Long-Term Support) and
future LTS releases, will provide stable and supported platforms for production applications.
Yes, .NET 6 is the continuation and evolution of .NET Core. .NET 6 is the next major release after
.NET 5, and it represents the ongoing development and unification of the .NET platform. Here’s how
.NET 6 relates to .NET Core:
• Continuation of .NET Core: .NET 6 builds upon the foundation of .NET Core and incorporates
its features, benefits, and improvements.
• Unification: .NET 6 is part of the effort to unify the capabilities of .NET Core and .NET
Framework into a single platform. It carries forward the cross-platform compatibility,
performance enhancements, and modern development practices introduced in .NET Core.
• Name Change: With the release of .NET 5, Microsoft officially dropped the “Core” from the
name, signifying that the unification process was well underway. .NET 6 continues this trend,
emphasizing the unified nature of the platform.
• New Features: .NET 6 introduces new features, improvements, and optimizations over .NET
Core. It includes enhancements to ASP.NET Core, Entity Framework Core, and other
components.
• Compatibility and Migration: While .NET 6 is designed to be largely compatible with .NET
Core, some adjustments or considerations might be needed when migrating applications
from earlier versions.
• Long-Term Support (LTS): .NET 6 includes a Long-Term Support (LTS) release, which means
that certain versions of .NET 6 will be designated as LTS and will receive stable and
supported updates for an extended period.
In summary, .NET 6 is the evolution of .NET Core, representing Microsoft’s ongoing efforts to provide
a modern, cross-platform, and unified development platform. It’s important to stay updated with
the latest information and documentation from Microsoft to fully understand the capabilities and
features of .NET 6 and its relationship with previous versions of .NET Core.
• Modular and Lightweight Architecture: .NET Core was designed with a modular and
lightweight architecture from the ground up. It includes only the necessary components and
features, which results in reduced overhead and better performance.
• Optimized Just-In-Time (JIT) Compilation: .NET Core’s JIT compiler has been optimized to
generate highly optimized machine code, resulting in faster execution of application code.
This can lead to quicker startup times and improved runtime performance.
• Single Binary and Self-Contained Deployment: .NET Core allows you to deploy applications
as single, self-contained executables with all necessary dependencies. This reduces the
overhead of loading and managing assemblies, contributing to faster application startup.
• Runtime and Garbage Collection Enhancements: .NET Core includes runtime and garbage
collection mechanism enhancements, resulting in more efficient memory management and
reduced overhead.
• Reduction in Legacy and Unused Features: .NET Core dropped support for legacy features
and technologies, which allowed developers to build applications without the burden of
maintaining backward compatibility. This reduction in legacy code and unused features can
lead to improved performance.
• Open Source and Community Contributions: The open-source nature of .NET Core
encourages community contributions, which can lead to performance improvements and
optimizations contributed by developers from various backgrounds.
• Language and Compiler Improvements: .NET Core introduced language features and
compiler enhancements that can lead to more efficient code generation and execution.
It’s important to note that performance improvements can vary depending on the specific use case,
application design, and workload. While .NET Core generally offers better performance than the
.NET Framework, the framework’s choice should also consider other factors such as platform
compatibility, development requirements, and ecosystem support.
Migrating from .NET Framework to .NET Core (or its successor, .NET 5 and beyond) can offer several
benefits, especially if you’re looking to modernize your applications and take advantage of the latest
development practices, performance improvements, and cross-platform capabilities. Here are some
reasons why you might consider migrating from .NET Framework to .NET Core:
• Modern Development Practices: .NET Core encourages modern development practices like
microservices architecture, containerization, and cloud-native development. Migrating can
enable you to adopt these practices and build more scalable, maintainable, and efficient
applications.
• Containerization and Cloud-Native: .NET Core works well with containerization technologies
like Docker, making it easier to create and deploy applications that can be run consistently
across different environments, including on-premises and in the cloud.
• Reduced Footprint: .NET Core has a smaller footprint compared to the full .NET Framework.
This can lead to more efficient resource utilization and deployment, which is particularly
important for microservices and cloud-based applications.
• Side-by-Side Deployment: With .NET Core, you can deploy multiple versions of the runtime
side by side, reducing the risk of compatibility issues and enabling easier updates.
• Open Source and Community: .NET Core is open source and has an active community of
contributors. This can lead to faster development cycles, bug fixes, and enhancements
driven by the community.
• Long-Term Support (LTS) Releases: .NET Core offers Long-Term Support (LTS) releases that
provide stability and extended support for production applications, ensuring that you can
confidently maintain and update your applications.
• Future-Proofing: As Microsoft’s focus has shifted towards .NET Core and its evolution into
.NET 5 and beyond, migrating to the latest platform can ensure that your applications stay
current and compatible with future technologies.
• Ecosystem Evolution: The .NET ecosystem is evolving, and future innovations and
advancements are more likely to be introduced in .NET Core and its successors, ensuring
that you can take advantage of the latest features and capabilities.
While migrating from .NET Framework to .NET Core offers many benefits, it’s important to note that
the migration process can involve challenges and considerations, including potential code changes,
adjustments to third-party dependencies, and compatibility testing. The decision to migrate should
be based on a thorough assessment of your application’s needs, the benefits of the new platform,
and the resources required for the migration process.
In this article, I will briefly introduce the Model View Controller Pattern and ASP.NET Core
MVC Framework. MVC is a Design Pattern, and ASP.NET Core MVC is a framework based on the MVC
Design Pattern. As part of this article, we will discuss the following pointers.
1. What is MVC?
5. When to Choose ASP.NET MVC and When to Choose ASP.NET Core MVC?
What is MVC?
MVC stands for Model View and Controller. It is an Architectural Design Pattern, which means it is
used at the application’s architecture level. So, MVC is not a programming language, not a
Framework. It is a Design Pattern. When we design an application, we first create its architecture,
and MVC plays an important role in designing that architecture.
The MVC Design Pattern is used to develop interactive applications. An interactive application
involves user interaction, and based on the user interaction, some event handling occurs. The most
important point you need to remember is that it is not only used for developing Web-Based
Applications; we can also use this MVC Design Pattern to develop Desktop or Mobile-Based
applications.
The MVC (Model-View-Controller) Design Pattern was introduced in the 1970s. It divides an
application into three major components: Model, View, and Controller. The main objective of the
MVC Design Pattern is the separation of concerns. This means the Domain Model and Business Logic
are separated from the User Interface (i.e., View). As a result, maintaining and testing the
application become simpler and easier.
Let’s look at an example to understand how the MVC Design Pattern works in an ASP.NET Core MVC
application. We want to design an application that displays the student details on a web page, as
shown below.
The Controller is the Component in the MVC design pattern that handles the incoming request. The
controller components do several things to handle the request. The controller component creates
the model that is required by a view. The model is the component in the MVC design pattern, which
basically contains classes that are used to store the domain data or, you can say, business data. In
the MVC design pattern, the Model component also contains the required logic to retrieve data from
a database.
Once the controller creates the model, it selects a view to render the domain or model data. While
selecting a view, it is also the controller’s responsibility to pass the model data. In the MVC design
pattern, the view’s only responsibility is rendering the model data. So, in MVC, the view is the
component responsible for generating the necessary HTML to render the model data. Once the view
generates the HTML, that HTML is sent to the client over the network who initially made the
request.
The three major components of an ASP.NET Core MVC Application are the Model, View, and
Controller. Let’s discuss each component of the MVC design pattern in detail.
Student.cs
namespace ASPNETCoreMVCApplication.Models
StudentBusinessLayer.cs
namespace ASPNETCoreMVCApplication.Models
{
StudentID = StudentID,
Name = "James",
Gender = "Male",
Branch = "CSE",
Section = "A2",
};
return student;
In our example, we use the Student class to hold the student data in memory. The
StudentBusinessLayer class manages the student data, performs the CRUD operation, Validates the
Student data, etc.
So, in short, we can say that a Model in the MVC Design Pattern contains a set of classes used to
represent the data and the logic to manage those data. In our example, the Student class represents
the data. The StudentBusinessLayer class manages the student data, validates it, and stores it in the
database.
• Respond to instructions from the controller to update itself (e.g., updating data points).
Role of View in MVC Design Pattern:
The View is the Component in the MVC Design pattern that contains the logic to represent the
model data as a user interface with which the end-user can interact. Basically, the view renders the
domain data (i.e., business data) provided by the controller. There should be minimal logic (you
should not write any business logic, calculation logic, validation logic, etc.) within views, and any
logic in them should only be related to presenting the content.
For example, we want to display Student data on a web page. The student model carried the student
data to the view. As already discussed, the view’s one and only responsibility is to render the model
data, in this case, student model data. The following code does the same thing.
@model ASPNETCoreMVCApplication.Models.Student
<html>
<head>
<title>Student Details</title>
</head>
<body>
<br />
<br />
<table>
<tr>
<td>@Model.StudentID</td>
</tr>
<tr>
<td>Name: </td>
<td>@Model.Name</td>
</tr>
<tr>
<td>Gender: </td>
<td>@Model.Gender </td>
</tr>
<tr>
<td>Branch: </td>
<td>@Model.Branch</td>
</tr>
<tr>
<td>Section: </td>
<td>@Model.Section </td>
</tr>
</table>
</body>
</html>
• Display the data provided by the controller in a format suitable for interaction.
• Send user inputs (like button clicks or data entries) to the controller.
• Update the visual presentation when the data in the model changes.
The Controller is the component in an MVC application that handles the incoming HTTP Request.
Based on the user action, the respective controller might work with the model, select a view to
render the information, and then send the response back to the user who initially made the request.
So, the Controller is the component that will interact with both the models and views to control the
application execution flow.
In ASP.NET Core MVC Application, a Controller is a .cs (for C# language) file with some methods
called Action Methods. When a request comes on the controller, the controller’s action method
handles those requests. In our example, when the user issued a request, the following URL
https://localhost:7132/Student/Details/2
Then, that request is mapped to the Details action method of the Student Controller using the
Routing defined for our application. We will discuss Routing in detail in our coming articles. For now,
look at the following Controller code:
using ASPNETCoreMVCApplication.Models;
using Microsoft.AspNetCore.Mvc;
namespace ASPNETCoreMVCApplication.Controllers
{
StudentBusinessLayer studentBL = new StudentBusinessLayer();
return View(studentDetail);
As you can see in the example, the Student Controller creates the Student object within the Details
action method. So, here, the Student is the Model. The controller uses the StudentBusinessLayer
class to fetch the Student data from the database.
Once the controller creates the Student model with the necessary student data, it passes the
Student model to the Details view. The Details view then generates the necessary HTML to present
the Student data. Once the HTML is generated, it is sent to the client over the network who initially
made the request.
Advertisements
• Handle user input and convert it to commands for the Model or View.
• Decide what response to send back to a user when a user makes a browser request.
• Update the Model when the user manipulates it through the View.
• Select the appropriate View to present the data from the Model.
Note: The Controller and View depend on the Model in the MVC Design Pattern, but the Model
never depends on either View or Controller. This is one of the main reasons for the separation of
concerns, which allows us to build and test the model independently of the visual presentation.
The ASP.NET Core MVC Framework comes with some amazing features. They are as follows:
Advertisements
• Open Source: The ASP.NET Core MVC Framework is open source, which is the main reason
for its popularity. The Entire Source Code of ASP.NET Core MVC Framework is available
at https://github.com/aspnet, and you are free to download the source code; even if you
want, you can also modify and compile your own version.
• Built-In Dependency Injection: ASP.NET Core has built-in support for dependency injection,
which helps manage dependencies between objects, making the system more modular,
scalable, and testable.
• Rich Routing: ASP.NET Core MVC provides a robust routing mechanism that allows
developers to control web application URLs. It supports pattern-based URL mapping, which
helps define SEO-friendly URLs.
• Support for Web APIs: ASP.NET Core MVC can be used to develop RESTful HTTP services. It
fully supports formatting response data as JSON or XML and can easily handle different
content types with content negotiation.
• Tag Helpers: Tag Helpers enable server-side code to participate in creating and rendering
HTML elements in Razor files.
When to Choose ASP.NET MVC and When to Choose ASP.NET Core MVC?
Choosing between ASP.NET MVC and ASP.NET Core MVC depends on various factors, including
project requirements, existing infrastructure, performance needs, and future maintenance
considerations. The following are some of the guidelines to help you decide:
ASP.NET MVC:
1. If you are currently working on an existing application with ASP.NET MVC and would like to
expand the functionalities by adding new features.
2. If your team is familiar with ASP.NET MVC Framework but has yet to gain experience with
ASP.NET Core MVC.
3. If you want, your application will only be compatible with devices and servers that run on
the Windows operating system.
1. If you have a preference for utilizing a framework that is completely open source.
2. If you want your application to be able to be developed and hosted on any operating
system.
4. If you are looking for an application development framework with a long development
roadmap ahead of it, look at .NET’s roadmap. Microsoft has already provided it for the next
five years.
A Controller is a special class in the ASP.NET Core Application with .cs (for C# language) extension. In
the ASP.NET Core MVC Application, the controller class must be inherited from the Controller base
class. In ASP.NET Core MVC, the Controller base class provides many properties, methods, and
features that handle HTTP requests and produce responses in our application. It provides Action
Result Methods, Model State Management, Validation, TempData, ViewBag, ViewData, etc. A
controller is a class that:
Controllers in the MVC Design Pattern handle the incoming HTTP Request, work with the model, and
select a view to render. When the client (browser) sends a request to the server, that request first
goes through the request processing pipeline. Once the request passes the request processing
pipeline (i.e., Middleware Component Registered into the Pipeline), it will hit the controller. Inside
the controller, there are lots of methods (called action methods) that handle the incoming HTTP
Requests. The action method inside executes the business logic and prepares the response, which is
sent back to the client who initially requested it. For a better understanding, please have a look at
the following diagram.
The Controllers in the ASP.NET Core MVC Application logically group similar types of actions
together. This grouping of similar types of action together allows us to define sets of rules, such as
caching, routing, and authorization, which will be applied collectively.
If you create the ASP.NET Core Application using the MVC Project Template, it will create
HomeController within the Controllers folder by default. But if you create the ASP.NET Core
Application with the Empty Project template, then by default, you will not find the Controllers folder
in your project. As we discuss everything from scratch, we will create the ASP.NET Core Application
with Empty Template and manually add the Controllers folder and the Controllers.
To create a new Empty ASP.NET Core Web Application, open Visual Studio 2022 and click the Create
a new project tab, as shown in the image below.
Once you click on the Create a new project tab, the Create a new project window will open. Select
the ASP.NET Core Empty project template in this window and click the Next button, as shown in the
image below.
Once you click on the Next button, it will open the Configure Your New Project window. Here, you
must provide the necessary information to create a new project. First, give an appropriate name for
your project (FirstCoreMVCWebApplication), set the location where you want to create this project,
and the solution name for the ASP.NET Core Web application. And finally, click on the Create button,
as shown in the image below.
Once you click on the Next button, it will open the Additional Information window. Here, you need
to select .NET Framework. You also need to check the Configure for HTTPS and do not use top-level
statements check boxes. Finally, click the Create button, as shown in the image below.
Once you click the Create button, a new ASP.NET Core Web Application will be created in Visual
Studio 2022 using .NET 8. The project will have the following file and folder structure.
Once you create the ASP.NET Core Empty Project, we need to add the Controllers folder to create
our Controllers. To do so, right-click on the project and then select the add => new folder option
from the context menu, which will add a new folder to your project. Just rename the folder
as Controllers.
Once you create the Controllers folder, we need to add a controller (StudentController) inside this
Controllers folder. To do so, right-click on the Controller folder and select the Add =>
Controller option from the context menu, which will open the Add Controller window, as shown in
the below image. Here, we will create the MVC Controller with the Empty template. So, select
the MVC Controller – Empty option and click the Add button, as shown in the image below.
As you can see in the above image, we have three templates for creating an MVC controller. So you
can use any of the following three templates:
2. MVC Controller with read/write actions: This template will create the controller with five
action methods to create, read, update, delete, and list entities.
3. MVC Controller with views, using Entity Framework: This template will create an MVC
Controller with actions and Razor views to create, read, update, delete, and list entities using
Entity Framework.
Once you click on the Add button, it will open the below window where you need to select
the Controller Class – Empty option and give a meaningful name to your controller. Here, I give the
name as StudentController and click on the Add button. The Controller name should be suffixed
with the word Controller.
Once you click the Add button, StudentController will be Added to the Controllers folder, as shown
in the image below.
Understanding StudentController:
Now, let us understand the StudentController class and its different components. Open
the StudnetController.cs class, and you should get the following default code.
As you can see in the above image, the StudentController class is inherited from the Controller base
class. This controller base class is present in Microsoft.AspNetCore.Mvc namespace, which is why it
imports that Microsoft.AspNetCore.Mvc namespace. Now right-click on the Controller base class
and select Go to the definition, and you will see the following definition of the Controller class.
As you can see in the above image, the Controller is an abstract class having many methods (Json,
View, PartialView, OnActionExecuting, ViewComponent, etc.) and properties (TempData, ViewBag,
ViewData, etc.). The point that you need to remember is that these methods and properties will be
used when we are working with ASP.NET Core MVC Application. Again, if you look, this Controller
class is inherited from the ControllerBase class.
Let us see the ControllerBase class definition as well. Right-click on the ControllerBase class and
select Go to definition, and you will see the following definition. Here, you will see the RequestData,
Response, Request, ModelState, Routing, Model Binder, HttpContext, and many more properties
and methods, which we will use as part of our ASP.NET Core MVC Application.
1. Naming Convention: Controllers are typically named with the suffix Controller, like
HomeController or ProductController.
I hope you now have clarity on ASP.NET Core MVC Controllers. Let’s move forward and understand
the next topic, Action Methods.
All the public methods of a controller class are known as Action Methods. They are created for a
specific action or operation in the application. The Controller class can have many related action
methods. For example, adding a Student is an action. Modifying the student data is another action.
Deleting a student is another action. So, all the related actions should be created inside a particular
controller.
An action method can return several types. Let us modify the HomeController as shown below,
where one method returns all the student details. Intentionally, we returned a string from this
method, but as we progress in this course, we will discuss the real implementation of this method.
But for now, we return a string just for learning purposes.
USING MICROSOFT .A SPN ETC ORE .MVC ;
When our application receives an HTTP Request, the controller action method handles it. So, when
we say we are hitting a controller, we are hitting its action method. The default structure
is http:domain.com/ControllerName/ActionMethodName.
As we are working with the development environment using Visual Studio, the domain name will be
our local host with some available port numbers. So, if we want to access the GetAllStudents action
method of the HomeController, then the
URL: http://localhost:<portnumber>/student/GetAllStudents
Let us prove this. You will not get the output if you run the application and navigate to the above
URL. This is because we created this project using the ASP.NET Core Empty Project template. By
default, the Empty Project template will not add the required MVC Service and Middleware
Components to the application processing pipeline.
Open the Program.cs class file and then copy and paste the code below into it, adding the required
MVC service to the dependency injection and the MVC middleware to the request processing
pipeline.
// ENABLE ROUTING MIDDLEWARE , WHICH MATCHES INCOMING HTTP REQUESTS TO ENDPOINTS DEFINED IN
THE APPLICATION
// THIS MEANS IF NO SPECIFIC ROUTE IS PROVIDED , IT WILL DEFAULT TO HOMECONTROLLER AND INDEX
ACTION
PATTERN : "{ CONTROLLER =HOME }/{ ACTION=I NDEX}/{ ID?}" // URL PATTERN FOR THE ROUTE
);
// RUN THE APPLICATION , WHICH BLOCKS THE CALLING THREAD AND STARTS LISTENING FOR INCOMING HTTP
REQUESTS
APP.RUN();
With the above change in place, now run the application and navigate to the
URL http://localhost:<portnumber>/student/GetAllStudents, and you should get the output as
expected, as shown in the image below.
Please look at the following image to better understand how the above URL mapped to the Student
Controller’s GetAllStudents action method.
How to Pass Parameters in Action Methods?
Let us understand this with an example. Now, we want to search for students based on their names.
To do so, add the following action method inside the Student Controller.
In this case, the query string parameter name is mapped with the GetStudentsByName action
method name parameter. In our upcoming articles, we will discuss parameter mapping, default
mapping, and more.
Whenever we need to define a new group of actions or operations in our applications, we must
create a new controller. For example, to do operations of students, we can create a Student
Controller. To manage the security of your application, like login, logout, etc., you can create a
Security Controller.
It depends on the application. At least one controller is required to perform operations. Maximum n
number of Controllers we can have into one application.
We have discussed creating and using Controllers in ASP.NET Core MVC Applications. We also
understand that the Controller Action Method will handle the incoming HTTP Request. But if you
look at the controller, you will see that Controller is a class inherited from the Controller Base class,
and this class has a method called Action Method.
We also know that if we want to invoke a method (non-static), then we need an instance of that
class. Now, the question is, who, when, and how created the Controller class instance, and how is
the action method called using that instance? Let us proceed and understand this with an example.
To create an ASP.NET Core MVC Application, we need to add the required MVC Services and
Middleware Components into the Request Processing Pipeline. For example, you can add the MVC
services using the following statement within your Main method of the Program.cs class file.
Then, we need to configure the MVC Middleware into the Request Processing Pipeline. For example,
the following code will add the MVC Middleware Component to the Application Processing Pipeline.
So, in the ASP.NET Core MVC Web Application, the MVC Middleware Component receives an HTTP
Request when the client sends an HTTP Request. Once the MVC Middleware Component receives
the request, based on routing, it selects the controller and action method to execute.
However, in order to execute the action method, the MVC Middleware must create an instance of
the selected controller. This makes sense, as we know that if we want to invoke a non-static method,
we need an instance of the class. This is not different from executing a controller action method.
The MVC Middleware uses Reflection to create an instance of the Controller class. This will use the
following IControllerActivator class. As you can see, this interface provides three methods: Create,
Release, and ReleaseAsync.
object Create(ControllerContext context):
• This method creates an instance of a controller using the provided ControllerContext. The
ControllerContext parameter provides contextual information about the current request and
the controller being created. It includes information like the HTTP context, route data, and
action descriptor (it contains detailed information about the action method, which the
framework uses to process HTTP requests and route them to the appropriate action
method). The method returns an instance of the controller.
• The ASP.NET Core framework calls this method to create a controller instance. The
implementation can use the ControllerContext to determine how to create the controller,
involving dependency injection or other custom logic.
• This method is responsible for releasing a controller instance and providing a way to perform
any necessary cleanup or disposal of the controller. The ControllerContext parameter
provides contextual information about the current request and the controller being
released. This object parameter is the instance of the controller that needs to be released.
This method does not return a value.
• This method is called by the ASP.NET Core framework to release a controller instance after it
has been used. The implementation can include any necessary cleanup or disposal logic,
such as calling Dispose on the controller if it implements IDisposable.
• The ASP.NET Core framework calls this method to release a controller instance after it has
been used asynchronously. The implementation can include any necessary asynchronous
cleanup or disposal logic.
DefaultControllerActivator
Now, the above interface is implemented by the DefaultControllerActivator class, which implements
the IControllerActivator interface methods and provides the logic to create and release the
controller. If you go to the definition of DefaultControllerActivator class, then you will see the
following.
As you can see, this class provides implementations for the IControllerActivator interface methods.
This is how the controller instance is created in the ASP.NET Core MVC Application.
In this article, I will discuss the Models in ASP.NET Core MVC Applications with Examples. Please
read our previous article discussing Controllers in ASP.NET Core MVC Applications. If your
application does not have data, then there is no need for a model. If your application has data, then
you need a model. We will work with the example we created in our Controller in ASP.NET Core
MVC article.
In the ASP.NET Core MVC application, a model is a class with a .cs (for C#) extension that defines the
Properties and behaviors of the data entities in your application. These are simple classes that
represent the objects in your application. For example, a Product model might contain properties
such as ID, Name, Price, and methods that define operations related to a product.
That means the Models in the ASP.NET Core MVC Application contain a set of classes representing
the domain data (you can also say the business data) and logic (validation, business, and data access
logic) to manage the domain/business data. The Model is the component in the MVC Design pattern
used to manage the data, i.e., the state of the application in memory.
If you are working with any web application based on the MVC design pattern, then three things are
common in that MVC application: Model, View, and Controller. The Controllers are used to manage
the overall flow of the MVC Application. Models are responsible for storing the data that is used on
Views. Views are the HTML Pages that get rendered into the client’s browser. In the browser, we
generally perform two operations. First, we display the data to the user; second, we get the data
from the user. For both these operations, models are used.
Where Will We Create the Models in the MVC Application?
It is not mandatory, but creating all the Model classes within the Models folder is a good
programming practice. Even though you can also create a separate class library project, put all the
model classes in that class library project, and refer to that class library project in your MVC
application. We will discuss this as we progress in this course.
When you create a new ASP.NET Core Web Application using the Model-View-Controller Template,
all the model classes are created inside the Models folder by default. We are also going to follow this
naming convention. Let us see how to create and work with models in an ASP.NET Core MVC
Application.
Right-click on your project, then select add => new folder option from the context menu to add a
new folder. Then, rename the folder name as Models. Here, we want to create a model for
displaying student data. So, create a class file named Student.cs within the Models folder. Once you
create the Student model, then the folder structure of your application should look as shown below.
Now open the Student.cs class file and then copy and paste the following code. As you can see, this
is a very simple class having only 5 properties to hold the student information.
This is our student model, which will store the student data in memory. As we already discussed, the
model also contains business logic to manage the data. So, in our example, to manage the student
data, i.e., to perform the CRUD operation on the student data, we will use the following
IStudentRepository interface.
Right-click on the Models folder and add an interface named IStudentRepository.cs. Once you
create the interface, copy and paste the following code.
As you can see, we created the above interface with one method, the GetStudentById() method,
which retrieves the student details by the student ID.
Let us create an implementation class for the above IStudentRepository interface. In our upcoming
article, we will discuss retrieving student details from a database. But for this demo, let’s hardcode
the student details. So, create a class file names StudentRepository.cs within the Models folder and
then copy and paste the following code into it.
{
NEW S TUDENT() { S TUDENT I D = 101, N AME = "JAMES", B RANCH = "CSE", S ECTION = "A", G ENDER =
"MALE" },
NEW S TUDENT() { S TUDENT I D = 102, N AME = "S MITH", BRANCH = "ETC", S ECTION = "B", G ENDER =
"MALE" },
NEW S TUDENT() { S TUDENT I D = 103, N AME = "DAVID", B RANCH = "CSE", S ECTION = "A", G ENDER =
"MALE" },
NEW S TUDENT() { S TUDENT I D = 104, N AME = "S ARA", B RANCH = "CSE", S ECTION = "A", G ENDER =
"FEMALE" },
NEW S TUDENT() { S TUDENT I D = 105, N AME = "PAM ", B RANCH = "ETC", S ECTION = "B", G ENDER =
"FEMALE" }
};
RETURN DATAS OURCE ().FIRST ORDEFAULT( E => E .S TUDENT I D == S TUDENT I D) ?? NEW STUDENT ();
Modify StudentController:
We already created a Controller named StudentController within the Controllers Folder. If you have
not created it, add a class file named StudentController within the Controllers folder. Then, modify
the StudentController as shown below to use the StudentRepository to retrieve the student details.
The Student and StudentRepository are in a separate namespace, so you must also include the
namespaces.
If you are directly coming to this article without reading our previous article, please modify the Main
method of the Program class as shown below. This registers the MVC Services and Middlewares to
the application request processing pipeline.
// ENABLE ROUTING MIDDLEWARE , WHICH MATCHES INCOMING HTTP REQUESTS TO ENDPOINTS DEFINED IN
THE APPLICATION
// THIS MEANS IF NO SPECIFIC ROUTE IS PROVIDED , IT WILL DEFAULT TO HOMECONTROLLER AND INDEX
ACTION
PATTERN : "{ CONTROLLER =HOME }/{ ACTION=I NDEX}/{ ID?}" // URL PATTERN FOR THE ROUTE
);
// RUN THE APPLICATION , WHICH BLOCKS THE CALLING THREAD AND STARTS LISTENING FOR INCOMING HTTP
REQUESTS
APP.RUN();
The way we implemented the GetStudentDetails method of the Student Controller is not loosely
coupled. That means tomorrow, if the implementation class of the IStudentRepository is changed,
we need to change the code in the Student Controller class, as both are tightly coupled. We can
overcome this problem by implementing the dependency injection design pattern that we will
discuss in our upcoming article.
• Data Representation: Models represent the data in memory used by your application. They
typically map to database tables or external data sources.
• Business Logic: Models may contain business rules and validation logic, ensuring data
integrity and consistency.
In this article, I will discuss ASP.NET Core MVC Views with Examples. Please read our previous article
before proceeding to this one, where we discussed Models in ASP.NET Core MVC Applications.
In this article, we will discuss the following concepts related to Views in ASP.NET Core MVC
Applications.
5. What is the difference between View() and View(object model) Extension Methods?
In Model-View-Controller (MVC) Design Pattern, the View is the component that contains logic to
represent the model data (the model data provided to it by a controller) as a user interface with
which the end-user can interact. That means View is used to render the user interface. Views are the
components in ASP.NET Core MVC that handle the application’s presentation logic. They are
responsible for rendering HTML markup sent to the client’s browser, typically written using the
Razor syntax.
A view in ASP.NET Core MVC Application is a file with “.cshtml” (for C# language) extension. The
meaning of cshtml = CS (C Sharp) + HTML. The View combines programming language (C#) and
HTML (Hypertext Mark-up Language). The Views in the ASP.NET Core MVC Application are generally
returned to the client from the Controller Action Method.
In ASP.NET Core MVC, there are four Types of Views. They are as follows:
• Razor Views: These are the most common views in ASP.NET Core MVC. They use the Razor
syntax (.cshtml files), which is a combination of HTML and C#.
• Partial Views: These are reusable view components that can be embedded within other
views. They are useful for rendering common elements like headers, footers, or navigation
menus.
• View Components: These are similar to partial views but more powerful. They can
encapsulate both the view and the logic needed to generate it.
• Layout Views: These provide a consistent look and feel across multiple views in your
application. They define a common template for your pages, including headers, footers, and
navigation bars. They define a common structure (like master pages in ASP.NET Web Forms).
By default, Views are available inside the Views folder, created in the project root directory. Usually,
views are grouped into folder names with the controller names. Each controller will have its own
folder in which the controller-specific view files will be stored. The controller-specific folders will be
created only within the Views folder.
Let’s say we have an ASP.NET Core MVC application with two controllers, i.e., HomeController and
StudentController. The HomeController is created with the following three action methods.
1. AboutUs()
2. ContactUs()
3. Index()
On the other hand, StudentController is created with the following four action methods.
1. Index()
2. Details()
3. Edit()
4. Delete()
Then, the following is the folder and file structure of the Views.
As you can see in the above image, a separate folder is created for each controller within the Views
Folder. The Home folder represents the HomeController, and the Student folder represents the
Student Controller.
• The Home folder contains the views for the Index, AboutUs, and ContactUs webpages.
Whenever a user requests one of these web pages, the Home Controller action method
determines which of the above three views to use to build the webpage and return it to the
user.
• Similarly, the Student folder contains the Index, Details, Edit, and Delete web page views. So,
whenever a user requests any of these web pages, the Student Controller action method
determines which of the above views to use to build the webpage and return to the user.
Note: Besides action-specific views, we have also provided partial views, layouts, and view
components. We will discuss each of these in our upcoming articles.
We will work with the same example we created in our ASP.NET Core Controllers article and
continue in Models in the ASP.NET Core article.
We have already created a Controller called Student Controller in the Controllers folder. Let us add a
new Controller named HomeController within the Controllers folder. At this time, your project
folder structure should look like the one below.
Open HomeController and then copy and paste the following code into it.
Advertisements
RETURN VIEW();
As you can see in the above HomeController class, we have only one action method, Index. The
return type of the Index() action method is ViewResult, which means it will return a view. To return a
view, we use the View() extension method, which belongs to the Controller Base Class.
Note: Views are typically returned from the Action method as a ViewResult, which is a type
of ActionResult. Your action method can create and return a ViewResult directly, but that isn’t
commonly done. Since most ASP.NET Core MVC Controllers are inherited from the Controller base
class, we can use the View helper method to return the ViewResult.
Now run the application and navigate to the “/Home/Index” URL or the default URL, and you will
see the following error.
Why Did We Get the Above Invalid Operation Exception?
Let us understand why we got the above exception. As we return a view from the Index action
method of Home Controller, by default, the ASP.NET Core MVC Framework will look for a file with
the name Index.cshtml in the following three locations.
1. First, it will look for the “Index.cshtml” file within the “/Views/Home” folder, as the action
method belongs to the Home Controller.
2. Then it will look for the “Index.cshtml” file in the “/Views/Shared/” folder.
3. Then it will look for the “Index.cshtml” file in the “/Pages/Shared/” folder.
If the requested “.cshtml” file is found in any of the above folders, the View generates the HTML and
sends it back to the client who initially made the request. On the other hand, if the requested file is
not found in any of the above locations, we will get the above error.
As we already discussed, views will be created in a special folder called Views. So, let us first add a
folder to the project root level with the name Views. To do so, right-click on the Project and
select Add => New Folder from the context menu. This will add a new folder, which we will then
rename Views.
As we already discussed, the Action Views will be created inside the folder whose name is the same
as the Controller’s name. We want to create a view for the Index action method of the Home
Controller. So, let us first add the Home folder inside the View folder. To do so, right-click on
the Views folder and then select the Add => New Folder option to add a new folder. Then, rename
the folder Home.
Once you have created the Home folder, then we need to create a view within this Home folder. In
ASP.NET Core MVC, we can add views in many different ways, and we will discuss them one by one.
So, right-click on the Home folder and then select the Add => View option, which will open the Add
View window, as shown in the image below. You need to select the Razor View and click the Add
button, as shown in the image below.
Once you click the Add button, it will open the Add Razor View window. Here, you need to give the
View name as Index, select the Empty (without model) template, uncheck the creation of a partial
view, use a layout page checkbox, and then click on the Add button as shown below.
Once you click the Add button, the Index.cshtml view should be created within the Home folder, as
shown in the image below.
Now open Index.cshtml file and then copy and paste the following code into it.
@{
LAYOUT = NULL;
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>INDEX</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
With the above changes in place, run the application, and you should get the expected output, as
shown in the image below.
What is View Discovery in ASP.NET Core MVC?
View Discovery in ASP.NET Core MVC is the process by which the framework determines which view
file to use when rendering a response to an HTTP request. This involves locating the appropriate
view file based on the action method and controller that handles the request.
If you go to the definition of the Controller base class, you will find four overload versions of the
View() method available, as shown in the image below.
Let us understand the use and significance of each of the above-overloaded versions of the View
Extension method.
If you use the View() or View(object model) extension method to return a view, it will look for the
view file with the same name as the action method name. If you want to pass model data, you need
to use the overloaded version of the View method, which takes the object model as an input
parameter; otherwise, you can use the View() extension method, which does not take any
parameter.
For example, in the code below, we are using the View() extension method, which does not take any
parameter to return a view from the Index action method of the Home Controller. So, by default, the
ASP.NET Core MVC framework will look for a view with the name Index.cshtml within the
“Views/Home” folder.
VIEW(STRING VIEWNAME) VS VIEW(STRING VIEWNAME, OBJECT MODEL ) EXTENSION METHODS:
If you want to return a view from an action method whose name is different than the action method
name, then you need to use either View(string viewName) or View(string viewName, object model)
Methods. If you want to pass model data to the view, you need to use the View(string viewName,
object model) method; otherwise, you can use the View(string viewName) method, which takes the
view name as a parameter.
To understand this concept, let’s create a view with the name Test.cshtml within the Home folder.
Please follow the same steps we follow to create the index.cshtml view. Once you created the
Test.cshtml view, then open the Test.cshtml file and copy-paste the below code in it.
@{
LAYOUT = NULL;
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>TEST</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
Now, modify the Index action method of the HomeController class as shown below to use the View
extension method, which takes the view name as a parameter.
Run the application and navigate to the “/Home/Index” URL. As shown in the image below, the
response comes from the test view.
Let us modify the Index action method of the Home controller, as shown below, to specify the
Absolute path of the view file. So here, the ASP.NET Core MVC framework will look for a view file
with the name “Test.cshtml” within the “Views/Home” folder.
Note: When using the absolute path, the .cshtml extension is mandatory.
When using an absolute path to reach the project’s root directory, you can use / or ~/. You can also
use any of the following, which will do the same thing.
Absolute Path vs Relative Path in ASP.NET Core While Specifying the View Name
In ASP.NET Core, when specifying the view name in a controller, you can use either an absolute or
relative path. Understanding the difference between these two types of paths and when to use each
is important for efficient and error-free coding.
Absolute Path:
• An absolute path is a complete path from the application’s root to the view file. It usually
starts with a forward slash (/) or a tilde and forward slash (~/), which represents the web
application’s root.
Relative Path
• A relative path is relative to the location of the calling controller. In ASP.NET Core, the
default convention is to look for views in a folder that matches the controller name within
the Views folder.
• Example: If you have a HomeController, calling return View(“Index”) will, by default, look for
the view in Views/Home/Index.cshtml.
When to Use:
• Use relative paths when the views are located in the conventional locations
(e.g., Views/[ControllerName]/[ViewName].cshtml).
• Use absolute paths when referencing a view outside the conventional locations or to ensure
the path remains valid regardless of controller location.
Let us add a new action to the HomeController with the name About. So, please modify the
HomeController as shown below.
RETURN VIEW();
}
PUBLIC VIEWRESULT ABOUT()
RETURN VIEW();
Now, right-click anywhere within the About action method and click on the Add View from the
context menu, as shown in the image below.
Once you click on the Add View, it will open the Add New Scaffolded Item window, as shown below.
In this window, you need to select the Razor View and click the Add button, as shown in the image
below.
Once you click on the Add button, the Add Razor View window will open. By default, the View will be
named About (action method name). Finally, click the Add button, as shown in the image below.
Once you click the Add button, it will add the About.cshtml file within the View/Home folder, as
shown in the below image.
Creating ASP.NET Core Application using MVC
Template
In this article, I will discuss How to Create ASP.NET Core Web Applications using MVC
(Model-View-Controller) Project Template and understand the Folder and File
Structure. Please read our previous article before proceeding to this article, where we
discussed ASP.NET Core Dependency Injection with Examples.
Creating an ASP.NET Core MVC Application:
As of now, we have discussed everything using the ASP.NET Core Empty Project
Template and understand the different components of an ASP.NET Core Application. We
also discussed Setting up the MVC Request pipeline in the ASP.NET Core Web
Application.
But the question is, do we need to manually set up everything to create an ASP.NET Core
MVC Application? The answer is NO. The ASP.NET Core Framework provides one built-
in Project Template called ASP.NET Core Web App (Model-View-Controller), which will
create an ASP.NET Core MVC Application for us with the required MVC setup. From now
on, in this ASP.NET Core MVC course, we will create the applications using the ASP.NET
Core Web App (Model-View-Controller) Project template.
Creating an ASP.NET Core Application using the MVC Project
Template:
To create an ASP.NET Core Web Application with the MVC Project template. First, open
Visual Studio 2022 and click the Create a new project tab, as shown in the image below.
Once you click on the Create a new Project tab, the following Create a new Project
window will open. From this window, select C#, All Platforms, and Web from the respective
dropdowns, as highlighted below. Select the ASP.NET Core Web App (Model-View-
Controller) as the project template, and click the Next button, as shown in the image
below.
Once you click on the Next button, it will open the Configure Your New Project window.
Here, you need to provide the necessary information to create a new ASP.NET Core
project. First, give an appropriate name for your project (SampleMVCWeb), set the
location where you want to create this project, and the solution name for the ASP.NET
Core Web application. And finally, click on the Create button, as shown in the image
below.
Once you click the Create button, the following Additional Information window will open.
Please select Framework .NET 8.0 (Long-term support) and Authentication
type None. You must also check the Configure for HTTPS and do not use top-level
statements check boxes. Finally, click the Create button, as shown in the image below.
Once you click the Create Button, the project will be created with the Web Application
(Model-View-Controller) template, i.e., the MVC template, with the following folder and file
structure.
builder.Services.AddControllersWithViews();
if (!app.Environment.IsDevelopment())
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production
scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
}
Running the MVC Application:
The ASP.NET Core Web APP (Model-View-Controller) Project template creates the Home
Controller with some views. Let’s run the application and see the output, as shown below.
Once you click on the Create a new Project tab, the following Create a new Project
window will open. From this window, select C#, All Platforms, and Web from the respective
dropdowns, as highlighted below. Select ASP.NET Core Web App (Model-View-
Controller), as highlighted below, and click the Next button, as shown in the image below.
Once you click on the Next button, it will open the Configure Your New Project window.
Here, you need to provide the necessary information to create a new ASP.NET Core
project. First, give an appropriate name for your project
(RoutingInASPDotNetCoreMVC), set the location where you want to create this project,
and the solution name for the ASP.NET Core Web application. And finally, click on
the Create button, as shown in the image below.
Once you click the Create button, the following Additional Information window will open:
Please select Framework .NET 8.0 (Long-term support) and Authentication
type None. You must also check the Configure for HTTPS and do not use top-level
statements check boxes. Finally, click the Create button, as shown in the image below.
Once you click the Create button, the project will be created using the Model-View-
Controller template with the following folder and file structure.
Modifying the Home Controller:
Once you have created the Project, next modify the Home Controller as follows:
using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPDotNetCoreMVC.Controllers
return View();
return View();
}
In the ASP.NET Core MVC Web Application, the controller action method handles
incoming HTTP Requests, i.e., URLs. For example, if we issue a request to
the /Home/Index URL, then the Index action method of the Home Controller class will
handle the request, as shown in the image below.
Similarly, if we issue a request to the /Home/Details/2 URL, then the Details action
method of the Home Controller class will handle the request, as shown in the image below.
Here, the parameter value 2 is automatically mapped to the id parameter of the Details
action method.
Now, the question that should come to your mind is, we have not explicitly defined any
routing rules for our application. Then how is this mapping done, i.e., how is
the /Home/Index URL mapped to the Index action method, and how is
the /Home/Details/2 URL mapped to the Details action method of the Home Controller
class? This is done by the MVC Routing Middleware Component, which is registered
into the Request Processing Pipeline.
Understanding Conventional-Based Routing in ASP.NET Core MVC
Web Application:
As we created the project with a Model-View-Controller template, the required MVC
Services and MVC Middleware components are, by default, added to the Request
Processing Pipeline. Also, the Required Routing Middleware Components are added to
the Request processing pipeline. So, if you open the Program class, you will find the
following code.
namespace RoutingInASPDotNetCoreMVC
builder.Services.AddControllersWithViews();
if (!app.Environment.IsDevelopment())
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production
scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
}
As you can see in the above code, MVC services are added by the following statement.
builder.Services.AddControllersWithViews();
Routing Middleware Components are added using
the UseRouting and MapControllerRoute methods. If you notice the
MapControllerRoute, you will see the following.
namespace RoutingInASPDotNetCoreMVC.Controllers
}
Now, the URL /student/index is mapped to the Index() action method of
the StudentController class, and the URL /student/details or /student/details/5 both
are mapped to the Details(int? id) action method of the StudentController.
Configure Multiple Conventional Routing in ASP.NET Core MVC
Application
In ASP.NET Core MVC, we can define multiple conventional routes to handle various URL
patterns in our application. This allows us to create more flexible and maintainable routing
configurations. This approach allows you to direct incoming requests to various controllers
and actions based on specific URL structures. For example, we want to access the Index
Action Method of the Student Controller using the following URL.
https://localhost:44359/Student/All
To achieve this, we can configure the MapControllerRoute method, as shown in the image
below. Here, you can see we have specified the pattern as Student/All and the default
controller and action name as controller = Student, action = Index.
Next, we want to access the Details of the action method for the Student Controller using
the following URL.
https://localhost:44359/StudentDetails/10
To achieve this, we can configure another MapControllerRoute method, as shown in the
below image. Here, you can see we have specified the pattern
as StudentDetails/{ID} and specified the default controller and action name as controller
= Student”, action = Details.
We need to access the rest of the controllers and actions using the following URL Pattern.
We also need to configure the default controller and action names as Home and Index.
https://localhost:44359/{Controller Name}/{Action method Name}
To achieve this, we can configure another MapControllerRoute method, as shown in the
below image. Here, you can see we have specified the pattern
as {controller}/{action}/{id:int?} and specified the default controller and action name
as controller = Home, action = Index.
The complete code of the Program class is given below.
namespace RoutingInASPDotNetCoreMVC
builder.Services.AddControllersWithViews();
if (!app.Environment.IsDevelopment())
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production
scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
//https://localhost:44359/Student/All
app.MapControllerRoute(
name: "StudentAll",
pattern: "Student/All",
);
//https://localhost:44359/StudentDetails/10
app.MapControllerRoute(
name: "StudentIndex",
pattern: "StudentDetails/{ID}",
);
//For Rest of the Controller Actions including the Default Home Controller Index
app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id:int?}",
);
app.Run();
}
With the above changes in place, run the application and navigate to the specific URLs,
and you will get the data as expected.
Note: Routes are evaluated in the order they are defined. Ensure the most specific routes
are defined first, as the request will be handled by the first route it matches. It’s a good
practice to give each route a unique name. This helps when generating URLs based on
route names. You can specify controller, action, and parameter default values. This is
useful for defining fallbacks for missing parts of the route.
Benefits of Conventional Routing in ASP.NET Core MVC:
• Simplicity: It reduces the need to define routes explicitly for every action
method or controller; instead, it uses default conventions.
• Predictable URLs: This feature encourages consistent URL patterns
across the application, making it easier to understand and debug routing
behavior.
• Centralized Configuration: All routing rules can be managed in one
place (Program.cs), promoting maintainability and consistency.
• Ease of Maintenance: As the application grows, maintaining a consistent
routing structure becomes easier, especially when new controllers and
actions are added.
Conventional-based routing is suitable for most ASP.NET Core MVC applications, where
the URL structure follows predictable patterns based on controller names, action methods,
and parameter names. It provides a straightforward way to handle typical routing
scenarios without the need for extensive attribute routing.
But what will you do if you want to execute some code or logic before or after the action
method is executed, as shown in the image below?
If that is your requirement, then you need to use Filters in your ASP.NET Core application.
Filters in ASP.NET Core Applications are the Attributes that allow us to inject logic or code
before or after an action method is executed.
Why are Filters in ASP.NET Core MVC?
In ASP.NET Core MVC, Filters are used to Perform cross-cutting concerns. They are as
follows:
• Caching
• Logging
• Error Handling
• Modifying the Result
• Authentication and Authorization, etc.
What are the Differences Between Filters and Middlewares in ASP.NET
Core?
Before proceeding further, we need to understand the differences between Filters and
Middleware Components in ASP.NET Core applications. The following are the Key
differences between Filters and Middleware Components:
Scope of Application (Where they Applied):
• Filters: Filters are primarily applied to individual controller actions or
controllers. They are used to add specific behaviors or concerns to
processing a single action or a group of actions within a controller.
• Middlewares: Middlewares are applied to the entire application’s request
processing pipeline. They can handle requests and responses globally,
regardless of the specific controller or action being invoked.
Execution Point (When they Execute):
• Filters: Filters execute within the ASP.NET Core Framework’s pipeline
and are part of the controller/action execution process. They are triggered
before or after the execution of a specific action method.
• Middlewares: Middlewares execute earlier in the Request Processing
Pipeline, typically before the request reaches the ASP.NET Core MVC
Controller action method. They can intercept requests and responses and
perform tasks at various stages of the request processing pipeline, such as
Routing, Authentication, Response Formatting, etc.
Purpose and Concerns (Why they are Used):
• Filters: Filters are designed to handle concerns specific to the ASP.NET
Core MVC framework, such as Logging, Authentication, Authorization,
Exception Handling, Caching, Custom Logic, etc.
• Middlewares: Middlewares are more general-purpose and can handle
many concerns, including Routing, Authentication, Request/Response
Logging, Compression, Security, etc.
Configuration (How they Configured):
• Filters: Filters are typically configured using attributes (e.g., [Authorize],
[AllowAnonymous], etc.) on controllers or action methods. You can also
register global filters in the Program Class.
• Middlewares: Middlewares are configured and ordered in the Program
class (e.g., UseHttpsRedirection(), UseAuthorization(),
MapControllers(), etc).
Execution Order (What is the Execution Order):
• Filters: The execution order for filters is decided based on the type of
filters you are applying to the controllers and action methods. So, the order
of Filters is not important.
• Middlewares: The execution order for middleware components is
determined by the order in which they are added to the IApplicationBuilder
pipeline, i.e., to the Request Processing Pipeline. So, the order of
Middleware Components is important.
So, Filters and Middleware Components serve different purposes and have different
scopes within an ASP.NET Core MVC application. Filters are more tightly integrated with
the ASP.NET Core MVC framework and are applied at the controller/action level. On the
other hand, Middleware Components are applied globally to the entire application.
Types of Filters in ASP.NET Core MVC
In ASP.NET Core MVC, there are several types of filters available that you can use to
modify the behavior in the request and response processing pipeline. The following are
the commonly used Filters in ASP.NET Core MVC Applications:
Authorization Filters in ASP.NET Core:
The Authorization Filter is used to perform Authentication and Authorization checks before
an action method is executed. Examples include AuthorizeAttribute for role-based or
policy-based authorization and AllowAnonymousAttribute to allow unauthenticated
users to access an action.
• [Authorize]: This Built-in Filter restricts access to actions or controllers for
UnAuthenticated Users. You can also specify Roles, Policies, or Claims
based on which it can also decide who can access specific resources.
• [AllowAnonymous]: This Built-in Filter allows unauthenticated users to
access actions or controllers.
• Custom Authentication: You can also create Custom Authentication. To
do so, we need to create a class implementing
the IAuthorizationFilter interface and provide implementations for
the OnAuthorization method, where we need to write the custom
authentication logic according to our business requirements.
Action Filters in ASP.NET Core:
The Action Filters in the ASP.NET Core MVC Application are executed before and after
an action method is executed. They perform tasks like Logging, Modifying the Action’s
Arguments, or Altering the Action’s Result.
In ASP.NET Core, you can create a Custom Action Filter in two ways: First, by creating a
class implementing the IActionFilter interface and providing implementations
for [OnActionExecuting] and [OnActionExecuted] methods. Second, by creating a
class inherited from the ActionFilterAttribute class and overriding
the [OnActionExecuting] and [OnActionExecuted] methods.
[OnActionExecuting] and [OnActionExecuted]: These are the two methods within a
Custom Action Filter to execute logic before and after an action method is called. The
OnActionExecuting method executes before the action method is invoked, and the
OnActionExecuted method executes after the action method is invoked.
How Do We Apply the Custom Filter to Controllers and Action Methods in
ASP.NET Core?
If the custom class is created by overriding the ActionFilterAttribute class, then it is an
Attribute, and we can directly apply that Custom Filter to the Action methods or Controllers.
However, you cannot apply Custom Action Filters (if the custom class is created by
implementing the ActionFilter interface) directly to the controllers and action methods.
For this, we need to use TypeFilter and ServiceFilter as built-in attributes.
TypeFilter and ServiceFilter are built-in attributes in ASP.NET Core that apply Custom
Action Filters as Attributes to controller actions or controllers. Later, as we progress, we
will discuss the differences between TypeFilter and ServiceFilter Attributes and how to
use them.
Result Filters in ASP.NET Core:
The Result Filters in ASP.NET Core MVC Application runs after the action method has
been executed but before the result is processed and sent to the client. This means you
can modify the view or the result data before it gets rendered to the output stream. They
are used for tasks such as Adding Headers to the response, Modifying the Result, etc.
In ASP.NET Core, you can create a Custom Result Filter in two ways: First, by creating a
class implementing the IResultFilter interface and providing implementations
for [OnResultExecuting] and [OnResultExecuted] methods. Second, by creating a
class inherited from the ResultFilterAttribute class and overriding
the [OnResultExecuted] and [OnResultExecuted] methods.
[OnResultExecuting] and [OnResultExecuted]: These are the two methods within a
Custom Result Filter to execute logic before and after the Result is generated.
The OnResultExecuting method executes before the result is generated, and
the OnResultExecuted method executes after the result is generated.
Exception Filters in ASP.NET Core:
The Exception Filters are executed when an unhandled exception occurs during the
execution of an action method. They are used for Logging, Error Handling, and Displaying
Different Error Pages Based on the Error Status Codes.
In ASP.NET Core, you can create a Custom Exception Filter in two ways: First, you can
create a class implementing the IExceptionFilter interface and provide implementations
for the [OnException] method. Second, by creating a class inherited from
the ExceptionFilterAttribute class and overriding the [OnException] method.
Where Can We Configure Filters in ASP.NET Core MVC?
In the ASP.NET Core MVC Application, Filters can be configured in the following three
places:
Configuring Filters at Controller Level:
We can apply filters at the controller level by decorating the controller with the Filter
attribute, as shown in the below code. When we apply the Filter at the controller level, it
will apply to all the actions of that controller.
[Authorize] // Authorization filter applied at the controller level
public class HomeController : Controller
{
public IActionResult Index()
{
// Action logic
}
}
Configuring Filters at Globally:
We can configure filters globally in the Program class. By adding filters as services, we
can ensure they are applied globally to all controllers and actions in our application.
Following is an example of configuring a global filter in the Program.cs class:
builder.Services.AddControllersWithViews(options =>
{
options.Filters.Add(new MyGlobalFilter());
});
Action Method Level:
We can also apply filters directly to individual action methods within our controller by using
the Filter Attribute, as shown in the below code. This allows us to apply specific filters only
to specific action methods.
public class MyController : Controller
{
[MyCustomFilter] // Custom filter applied to this action
public IActionResult MyAction()
{
// Action logic
}
}
Default Filters Execution Order in ASP.NET Core MVC
In ASP.NET Core MVC, filters are executed in a specific order known as the “Default
Execution Order“. The default execution order ensures filters are applied properly
throughout the request processing pipeline. The default execution order, from the earliest
to the latest in the pipeline, is as follows:
• Authorization Filters: Authorization filters are executed first. They are
responsible for checking whether the current user can access the requested
resource or action. If authorization fails, the request will be short-circuited,
and the action method will not be executed.
• Action Filters (Before Action Execution): Action filters with “Before
Action Execution” logic are executed before the action method is invoked.
These filters can perform tasks like logging, input validation, or pre-
processing data.
• Model Binding: Model binding occurs at this stage. It binds incoming data
to action method parameters and executes model validation.
• Action Execution: The action method itself is executed.
• Action Filters (After Action Execution): Action filters with “After Action
Execution” logic are executed after the action method completes its
execution. These filters can perform tasks like logging, post-processing
data, etc.
• Result Filters (Before Result Execution): Result filters with “Before
Result Execution” logic are executed before the action result is executed.
These filters can modify the result or perform additional processing.
• Action Result Execution: The action result, which can be a view or any
other result type, is executed.
• Result Filters (After Result Execution): Result filters with “After Result
Execution” logic are executed after the action result has been executed.
These filters can perform tasks like logging or post-processing of the result.
• Exception Filters (If an Exception Occurs): Exception filters are
executed if an unhandled exception occurs during the request’s processing.
These filters can handle the exception, log it, and return an appropriate error
response.
ASP.NET MVC Interview Questions and Answers
What is _ViewStart?
The _ViewStart.cshml page is used to serve a common layout page(s) for a group of
views. The code within this file is executed before the code in any view placed in the same
directory. This file is also recursively applied to any view within a subdirectory.
What are the different ways of rendering layout in ASP.NET MVC?
There are following four different ways of rendering layout in ASP.NET MVC:
Using _ViewStart file in the root directory of the Views folder:
The _ViewStart file within the Views folder is used to serve the default Layout page for
your ASP.NET MVC application. You can also change the default rendering of layouts
within _ViewStart file based on the controller as shown below:
@{
var controller =
HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToSt
ring();
string layout = "";
if (controller == "Admin")
{
layout = "~/Views/Shared/_AdminLayout.cshtml";
}
else
{
layout = "~/Views/Shared/_Layout.cshtml";
}
Layout = layout;
}
Adding the _ViewStart file in each of the directories
You can also set the default layout for a particular directory by putting the _ViewStart file
in each of the directories with the required Layout information as shown below:
Defining Layout within each view on the top
@{
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
Returning Layout from ActionResult
public ActionResult Index()
{
RegisterModel model = new RegisterModel();
//TODO:
return View("Index", "_AdminLayout", model);
}
What is the App_Start folder in ASP.NET MVC?
App_Start folder has been introduced in MVC4. It contains various configurations files like
as
BundleConfig.cs, FilterConfig.cs, RouteConfig.cs, WebApiConfig.cs for your application.
All these settings are registered within the Application_Start method of Global.asax.cs
file.
BundleConfig.cs – This is used to create and register bundles for CSS and JS files. By
default, various bundles are added in these files including jQuery, jQueryUI, jQuery
Validation, Modernizr, and Site CSS.
FIlterConfig.cs – This is used to register global MVC filters like error filters, action filters,
etc. By default, it contains the HandleErrorAttribute filter.
RouteConfig.cs – This is used to register various route patterns for your ASP.NET MVC
application. By default, one route is registered here named as Default Route.
Advertisements
WebApiConfig.cs – This is used to register various WEB API routes like ASP.NET MVC,
as well as set any additional WEB API configuration settings.
What are the different ways of returning/rendering a view in ASP.NET
MVC?
This is one of the Frequently asked ASP.NET MVC interview questions and answers.
There are four different ways of returning/rendering a view in ASP.NET MVC as given
below:
1. Return View() – This tells MVC to generate HTML to be displayed for the
specified view and sends it to the browser. This acts as a Server.Transfer()
in ASP.NET WebForm.
2. Return RedirectToAction() – This tells MVC to redirect to specified
action instead of rendering HTML. In this case, the browser receives the
redirect notification and make a new request for the specified action. This
acts like Response.Redirect() in ASP.NET WebForm.
Moreover, RedirectToAction constructs a redirect URL to a specific action/controller in
your application and use the routing table to generate the correct URL. RedirectToAction
causes the browser to receive a 302 redirect within your application and gives you an
easier way to work with your router table.
1. Return Redirect() – This tells MVC to redirect to a specified URL instead
of rendering HTML. In this case, the browser receives the redirect
notification and make a new request for the specified URL. This also acts
like a Response.Redirect() in ASP.NET WebForm. In this case, you have
to specify the full URL to redirect.
Moreover, Redirect also causes the browser to receive a 302 redirect within your
application, but you have to construct the URLs yourself.
1. Return RedirectToRoute() – This tells MVC to look up the specified route
into the Route table that is defined in global.asax and then redirect to that
controller/action defined in that route. This also make a new request like
RedirectToAction().
Points to Remember:
1. Return View doesn’t make a new request, it just renders the view without
changing URLs in the browser’s address bar.
2. The Return RedirectToAction makes a new request and the URL in the
browser’s address bar is updated with the generated URL by MVC.
3. Return Redirect also makes a new request and the URL in the browser’s
address bar is updated, but you have to specify the full URL to redirect
4. Between RedirectToAction and Redirect, the best practice is to use
RedirectToAction for anything dealing with your application
actions/controllers. If you use Redirect and provide the URL, you’ll need to
modify those URLs manually when you change the routing table.
5. RedirectToRoute redirects to a specific route defined in the Route table.
What is Area in ASP.NET MVC?
Areas were introduced in Asp.net MVC2 which allows us to organize models, views, and
controllers into separate functional sections of the application, such as administration,
billing, customer support, and so on. This is very helpful in a large web application, where
all the controllers, views, and models have a single set of folders and that becomes difficult
to manage.
Each MVC area has its own folder structure which allows us to keep separate controllers,
views, and models. This also helps the multiple developers to work on the same web
application without interfering with one another.
Advertisements
How to register Area in ASP.NET MVC?
Before working with the area, make sure you have registered your area within the
Application_Start method in Global.asax as shown below.
protected void Application_Start()
{
//Register all application Areas
AreaRegistration.RegisterAllAreas();
}
Always remember the order of registering the Areas must be on top so that all of the
settings, filters, and routes registered for the applications will also apply to the Areas.
What is Scaffolding?
We (developers) spent most of our time writing code for CRUD operations that are
connecting to a database and performing operations like Create, Retrieve, Update, and
Delete. Microsoft introduces a very powerful feature called Scaffolding that does the job
of writing CRUD operations code for us.
Scaffolding is basically a Code Generation framework. Scaffolding Engine generates
basic controllers as well as views for the models using Microsoft’s T4 template. Scaffolding
blends with Entity Framework and creates the instance for the mapped entity model and
generates code of all CRUD Operations. Further, we can edit or customize this auto-
generated code according to our needs. As a result, we get the basic structure for a
tedious and repetitive task.
Following are a few advantages of Scaffolding:
1. RAD approach for data-driven web applications.
2. Minimal effort to improve the Views.
3. Data Validation based on the database schema.
4. Easily created filters for the foreign key or boolean fields.
What are the differences between ViewData, ViewBag, TempData, and
Session?
This is one of the Frequently asked ASP.NET MVC interview questions and answers. In
ASP.NET MVC there are three ways – ViewData, ViewBag, and TempData to pass data
from the controller to view and in the next request. Like WebForm, we can also use
Session to persist data during a user session.
ViewData in ASP.NET MVC
public ViewDataDictionary ViewData { get; set; }
1. ViewData is a dictionary object that is derived from ViewDataDictionary
class.
2. The ViewData is used to pass data from the controller to the
corresponding view.
3. Its life lies only during the current request.
4. If redirection occurs then its value becomes null.
5. It’s required typecasting for getting data and check for null values to avoid
the error.
ViewBag in ASP.NET MVC
public Object ViewBag { get; set;}
1. ViewBag is a dynamic property that takes advantage of the new dynamic
features in C# 4.0.
2. Basically, it is a wrapper around the ViewData and also used to pass data
from the controller to the corresponding view.
3. Its life also lies only during the current request.
4. If redirection occurs then its value becomes null.
5. It doesn’t require typecasting for getting data.
TempData in ASP.NET MVC
public TempDataDictionary TempData { get; set; }
1. TempData is a dictionary object that is derived from the
TempDataDictionary class and stored in a short life session.
2. TempData is used to pass data from current request to subsequent
request (means redirecting from one page to another).
3. Its life is very short and lies only until the target view is fully loaded.
4. It’s required typecasting for getting data and check for null values to avoid
the error.
5. It’s used to store only one time messages like error messages, validation
messages.
Session in ASP.NET MVC
public HttpSessionStateBase Session { get;set; }
1. In ASP.NET MVC, Session is a property of Controller class whose type is
HttpSessionStateBase.
2. The session is also used to pass data within the ASP.NET MVC
application and Unlike TempData, it persists data for a user session until it
is timeout (by default session timeout is 20 minutes).
3. A session is valid for all requests, not for a single redirect.
4. It’s also required typecasting for getting data and check for null values to
avoid the error.
How to control Session behavior in ASP.NET MVC?
This is one of the Frequently asked ASP.NET MVC interview questions. By default,
ASP.NET MVC support session state. The session is used to store data values across
requests. Whether you store some data values within the session or not ASP.NET MVC
must manage the session state for all the controllers in your application that is time-
consuming. Since, the session is stored in the server-side and consumes server memory,
hence it also affects your application performance.
If some of the controllers of your ASP.NET MVC application are not using session state
features, you can disable session for those controllers and can gain slight performance
improvement of your application. You can simplify the session state for your application
by using available options for the session state.
SessionState attribute provides you more control over the behavior of session-state by
specifying the value of SessionStateBehavior enumeration as shown below:
Value Description
Default => The default ASP.NET behavior is used to determine the session state
behavior.
Disabled => Session state is disabled entirely.
ReadOnly => Read-only session state behavior is enabled.
Required => Full read-write session state behavior is enabled.
How is TempData related to Session in ASP.NET MVC?
In ASP.NET MVC, TempData uses a session state for storing the data values across
requests. Hence, when you will disable the session state for the controller, it will throw the
exception.
What is a View Engine in ASP.NET MVC application?
This is one of the Frequently asked ASP.NET MVC Interview Questions and Answers. A
View Engine in ASP.NET MVC application is used to translate the views to HTML and
then render the HTML in a browser.
The point that you need to remember is, the View Engine in ASP.NET MVC application
having its own markup syntax. As discussed, the View Engine in the ASP.NET MVC
application is responsible for converting the Views into HTML markup and then rendering
the HTML in a browser. Initially, the ASP.NET MVC framework comes with one view
engine i.e. web forms (ASPX) view engine and from the ASP.NET MVC3 framework a
new view engine i.e. Razor view engine comes. Now, it is also possible to use other third-
party view engines such as Spark, NHaml, etc.
How does the View Engine work in the ASP.NET MVC application?
This is one of the Frequently asked ASP.NET MVC Interview Questions and Answers.
Each and every view engine in ASP.NET MVC application has the following three major
components:
1. ViewEngine Class – The ViewEngine class implements
the IViewEngine interface and the responsibility of this class is locating the
view templates.
2. View Class – The View class implements the IView interface and the
responsibility of this class is to combine the template with data from the
current context and then convert it to HTML markup.
3. Template Parsing Engine – This parses the template and compiles the
view into executable code.
What is Razor View Engine?
The Razor Engine was introduced in ASP.NET MVC3. This is an advanced View Engine
that provides a new way to write markup syntax which will reduce the typing of writing the
complete HTML tag. the Razor syntax is easy to learn and much cleaner than Web Form
syntax. Razor uses @ symbol to write markup.
How to register Custom View Engine in ASP.NET MVC?
This is one of the Frequently asked ASP.NET MVC interview questions. In order to use
the custom View Engine, first, we need to register it in the Application_Start() method of
the global.asax.cs file so that the framework will use our custom View Engine instead of
the default one.
The output of the Index() action method will be cached for 20 seconds. If you will not define
the duration, it will cache it for by default cache duration 60 sec.
Output Caching Location
By default, content is cached in three locations: the web server, any proxy servers, and
the user’s browser. You can control the content’s cached location by changing the location
parameter of the OutputCache attribute to any of the following values: Any, Client,
Downstream, Server, None, or ServerAndClient.
Advertisements
By default, the location parameter has the value and which is appropriate for most of the
scenarios. But sometimes there are scenarios when you required more control over the
cached data.
How to allow users to submit HTML tags in ASP.NET MVC?
By default, ASP.NET MVC doesn’t allow a user to submit HTML for avoiding the Cross-
Site Scripting attack on your application. You can achieve it by using the ValidateInput
attribute and AllowHtml attribute. The ValidateInput attribute can enable or disable input
validation at the controller level or at any action method.
[ValidateInput(false)]
public class HomeController : Controller
{
public ActionResult AddArticle()
{
return View();
}
}
The ValidateInput attribute allows the Html input for all the properties and that is unsafe.
Since you have enabled Html input for only one-two properties then how to do this. To
allow Html input for a single property, you should use the AllowHtml attribute.
Advertisements
The SOLID Design Principles in C# help us solve most software design problems. These
principles provide multiple ways to remove the tightly coupled code between the software
components (between classes), making the software designs more understandable,
flexible, and maintainable.
This SOLID Design Principles Course is For whom:
This course is designed for Students, Beginners, Intermediates, and Professional
Software Developers who want to learn SOLID design principles step by step with real-
time examples. This tutorial provides a hands-on approach to the subject with step-by-
step programming examples that will assist you in learning and putting the acquired
knowledge into practice.
Advertisements
What is JIT?
1. JIT stands for Just-in-time.
2. JIT is the component of CLR that is responsible for converting MSIL code
into Native code or Machine code.
3. This Native code or Machine code is directly understandable by the
operating system.
Explain different types of .NET Framework.
The .Net framework is available in three different types
1. .NET Framework: This is the general version required to run .NET
applications on Windows OS only.
2. .NET mono Framework: This is required if we want to run .NET
applications on other OS like Unix, Linux, MAC OS, etc.
3. .NET Compact Framework: This is required to run .NET applications on
other devices like mobile phones and smartphones.
Note: MSIL is only CPU dependent and will run only on Windows OS only using .NET
Framework because .NET Framework is designed for Windows OS only.
There is another company known as “NOVEL” that designed a separate framework known
as “MONO Framework”. Using this framework we can run MSIL on different OS Like Linux,
UNIX, Mac, BSD, OSX, etc. .NET is platform-dependent using the .NET framework but
independent using the MONO framework.
What is not .NET?
1. .NET is not an Operating system.
2. It is not an application or package.
3. .NET is not a database.
4. It is not an ERP application.
5. .NET is not a Testing Tool.
6. It is not a programming language.
What is exactly .NET?
.NET is a framework tool that supports many programming languages and many
technologies. It supports 60+ programming languages. In 60+ programming languages, 9
are designed by Microsoft and the remaining are designed by Non-Microsoft.
Microsoft-designed programming languages are as follows
1. VB.NET
2. C#.NET
3. VC++.NET
4. J#.NET
5. F#.NET
6. Jscript.NET
7. WindowsPowerShell
8. Iron Phyton
9. Iron Ruby
Technologies supported by the .NET framework are as follows
1. ASP.NET (Active Server Pages.NET)
2. ADO.NET (Active Data Object.NET)
3. WCF (Windows Communication Foundation)
4. WPF (Windows Presentation Foundation)
5. WWF (Windows Workflow Foundation)
6. AJAX (Asynchronous JavaScript and XML)
7. LINQ (Language Integrated Query)
8. ASP.NET MVC (Model View Controller)
9. ASP.NET WEB API
What are the language and its need?
1. A language acts as the mediator between the programmer and the system.
2. It offers some rules and regulations for writing the program.
3. The language also offers some libraries which are required for writing the
program.
4. The collection of programs is called software.
What are Technology and its needs?
Technology is designed for a particular purpose. For example development of web-related
applications in .NET using the technology ASP.NET. But the technology does not offer
any specific rules for writing the programs. That’s why technology can’t be implemented
individually.
VB.NET, and C#.NET both are programming languages. Using these two languages we
can implement windows/desktop applications individually. Every language is having its
own compiler
VB.NET, C#.NET:
VB.NET and C#.NET both are programming languages. Using these two programming
languages we can develop windows applications.
ASP.NET:
1. ASP.NET is a part of the .NET Framework.
2. ASP.NET is a technology that provides a set of predefined classes. Using
these classes we can implement web applications.
3. ASP.NET is needed language support.
ADO.NET:
1. ADO stands for ActiveX Data Objects.
2. The ADO.NET is a .NET database technology.
3. ADO.NET provides a set of predefined classes. Using these predefined
classes we can perform the operations with the database server.
WCF:
1. WCF stands for Windows Communication Foundation.
2. The WCF is a distributed technology. Using this technology we can
implement SOA (Service Oriented Architecture) programming.
3. SOA programming provides communication between heterogeneous
applications.
4. Applications that are developed using different technologies or different
programming languages are known as heterogeneous applications.
WPF:
1. The WPF stands for windows presentation foundation.
2. WPF is a .NET technology using this technology we can create 2D, and
3D, graphics, and animations for windows applications.
3. Using this technology we can also create our own audio/video players and
also implement gaming applications.
LINQ:
1. LINQ stands for Language Integrated Query.
2. It is query-writing Technology.
3. LINQ offers to write queries in the programming code itself.
4. This concept is introduced in .NET framework 3.5
5. LINQ queries apply in database data and non-database data also.
What is Visual Studio?
Visual Studio is a Microsoft IDE tool that is needed to develop applications with the .NET
framework. The IDE integrates 3 features
1. Editor
2. Compiler
3. Interpreter
What is .Net?
1. .NET is a programming framework created by Microsoft that developers
can use to create applications more easily. The framework provides
libraries commonly used by developers. The .NET Base Class Libraries
(BCL) serves that purpose.
2. The .NET provides language interoperability across several programming
languages. Programs are written for .NET Framework and execute in a
software environment called Common Language Runtime (CLR).
3. CLR is the foundation of the .NET framework which provides services like
safety, memory management, garbage collection, and exception handling.
4. CLR manages the execution of code. The code that is managed by CLR is
called managed code. Unmanaged code does not get managed by CLR.
CLR’s interoperability helps to interact between managed and unmanaged
code.
5. Common Language Specification (CLS) and Common Type System (CTS)
as part of CLR. CTS is responsible for interpreting data types into a common
format. CLS provides the ability of code to interact with code that is written
with a different programming language.
What is the Just-In-Time (JIT) compilation?
The MSIL is the language that all of the .NET languages compile down to. After they are
in this intermediate language, a process called Just-In-Time compilation occurs when
resources are used from our application at runtime.
What is metadata?
Metadata describes every type and member defined in our code in a Multilanguage form.
Metadata stores the following information.
1. Description of assembly.
2. Identity (name, version, culture, public key).
3. The types that are exported
4. Other assemblies that this assembly depends on.
5. Security permissions are needed to run.
What is an assembly?
Assemblies are the building block of .NET framework applications; they form the
fundamental unit of deployment, version control, reuse, activation scoping and security
permissions.
What are the differences between managed code and unmanaged
code?
This is one of the frequently asked C# Interview Questions and Answers. Let us discuss
the difference between them.
Managed code/methods:
Machine instructions are in MSIL format and located in assemblies that will be executed
by the CLR and will have the following advantages
1. Memory management to prevent memory leaks in program code.
2. Thread execution
3. Code safety verification
4. Compilation.
Unmanaged code/ methods:
The Unmanaged codes are the instructions that are targeted for specific platforms.
Unmanaged code will exist in any of the formats.
1. COM/COM+ components
2. Win 32 Dlls/system DLLs
3. As these codes are in native formats of OS, these instructions will be
executed faster compared with JIT compilation and execution of managed
code.
What is C#?
C# is an object-oriented typesafe and managed language that is compiled by the .Net
framework to generate Microsoft Intermediate Language.
What is the difference between an EXE and a DLL?
This is one of the frequently asked C# Interview Questions and Answers. Let us
understand the difference between Exe and DLL. EXE is an executable file and can run
by itself as an application whereas DLL is usually consumed by an EXE or by another DLL
and we cannot run or execute DLL directly.
For example in .NET compiling a Console Application or a Windows Application generates
EXE, whereas compiling a Class Library Project or an ASP.NET web application
generates DLL. In the .NET framework, both EXE and DLL are called assemblies.
A DLL can be reused in the application whereas an exe file can never be reused in an
application. EXE stands for executable, and DLL stands for Dynamic Link Library
What’s the difference between IEnumerable<T> and List<T>?
1. IEnumerable is an interface, whereas List is one specific implementation
of IEnumerable. A list is a class.
2. FOR-EACH loop is the only possible way to iterate through a collection
of IEnumerable whereas List can be iterated using several ways. The list
can also be indexed by an int index. The element of a list collection can be
added to and removed from and have items inserted at a particular index
but these are not possible with a collection of type IEnumerable.
3. IEnumerable doesn’t allow random access, whereas List does allow
random access using the integral index.
4. In general, from a performance standpoint, iterating
through IEnumerable is much faster than iterating through a List.
Why is class an abstract data type?
A Class is an Abstract Data Type because it specifies what data members and member
functions (methods) contain in it (class), but it does not provide information on how those
are implemented. That makes Class Abstract and Class is User Defined DataType. So,
it’s an Abstract Data Type
What are the new features introduced in C# 7?
This is a very commonly asked C# interview question. This question is basically asked to
check if you are passionate about catching up with the latest technological advancements.
The list below shows the new features that are introduced in C# 7. Let’s have a look at the
new features that are introduced as part of C# 7
1. Out variables
2. Pattern matching
3. Digit Separators
4. Tuples
5. Deconstruction (Splitting Tuples)
6. Local functions
7. Literal improvements
8. Ref returns and locals
9. Generalized async return types
10. More expression-bodied members
11. Throw expressions
12. Discards
13. Async main
14. Default literal expressions
15. Inferred tuple element names
Why should you override the ToString() method?
This C# Interview Question is one of the most frequently asked .NET questions. All types
in .Net inherit from the System.Object class directly or indirectly. Because of this
inheritance, every type in .Net inherits the ToString() method from System.Object class.
To understand this better, please have a look at the example.
In the above example Number.ToString() method will correctly give the string
representation of int 10 when we call the ToString() method. If we have any user-defined
class like the Customer class as shown in the below example and when we call the
ToString() method the output does not make any sense i.e. in the output you simply get
the class name.
public class Customer
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
But what if we want to print the first name and last name of the customer when we call the
toString method on the customer object. Then we need to override the ToString() method,
which is inherited from the System.Object class. The code sample below shows how to
override the ToString() method in a class, that would give the output that we want.
public class Customer
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
What is the difference between string keyword and System.String
class?
Actually, there is no difference. The string keyword is an alias for System.String class.
Therefore System.String and string keywords both are the same, and we can use
whichever naming convention we prefer. The String class provides many methods for
safely creating, manipulating, and comparing strings.
Are string objects mutable or immutable?
String objects are immutable.
What do you mean by String objects are immutable?
This C# Interview question is frequently asked in .NET Interviews. String objects are
immutable means they cannot be changed once they are created. All of the String
methods and C# operators that appear to modify a string actually return the results in a
new string object. In the following example, when the contents of s1 and s2 are
concatenated to form a single string, the two original strings are unmodified. The +=
operator creates a new string that contains the combined contents. That new object is
assigned to the variable s1, and the original object that was assigned to s1 is released for
garbage collection because no other variable holds a reference to it.
string s1 = "First String ";
s1 += s2;
System.Console.WriteLine(s1);
System.Console.WriteLine(str2);
The output of the above code is “Hello” and not “Hello C#”. This is because, if you create
a reference to a string, and then “modify” the original string, the reference will continue to
point to the original object instead of the new object that was created when the string was
modified.
What is a verbatim string literal and why do we use it?
The “@” symbol is the verbatim string literal. Use verbatim strings for convenience and
better readability when the string text contains backslash characters, for example in file
paths. Because verbatim strings preserve newline characters as part of the string text,
they can be used to initialize multiline strings. Use double quotation marks to embed a
quotation mark inside a verbatim string. The following example shows some common uses
for verbatim strings:
string ImagePath = @"C:\Images\Buttons\SaveButton.jpg";
//Output: C:\Images\Buttons\SaveButton.jpg
Text written to be in
three lines.";
/* Output:
This is multiline
Text written to be in
three lines.
*/
int i = 0;
if(int.TryParse(str,out i))
else
{
}
What is the difference between int.Parse and int.TryParse methods?
The parse method throws an exception if the string you are trying to parse is not a
valid number whereas TryParse returns false and does not throw an exception if
parsing fails. Hence TryParse is more efficient than Parse.
What are Properties in C#? Explain with an example.
It is one of the most frequently asked C# Interview Questions. Properties in C# are class
members that provide a flexible mechanism to read, write, or compute the values of private
fields. Properties can be used as if they are public data members, but they are actually
special methods called accessors. This enables data to be accessed easily and still helps
promote the safety and flexibility of methods.
In the example below _firstName and _lastName are private string variables that are
accessible only inside the Customer class. _firstName and _lastName are exposed using
FirstName and LastName public properties respectively. The get property accessor is
used to return the property value, and a set accessor is used to assign a new value. These
accessors can have different access levels. The value keyword is used to define the value
being assigned by the set accessor. The FullName property computes the full name of the
customer. The FullName property is read-only because it has only the get accessor.
Properties that do not implement a set accessor are read-only.
The code block for the get accessor is executed when the property is read and the code
block for the set accessor is executed when the property is assigned a new value.
class Customer
get
return _firstName;
}
set
_firstName = value;
get
return _lastName;
set
_lastName = value;
get
}
}
set
_coutry = value;
class MainClass
CustomerObject.FirstName = "David";
CustomerObject.LastName = "Boon";
}
What are the different types of properties available in C#?
In C#, there are three types of Properties available. They are shown in the following
image.
1. Read-Only Properties: Properties without a set accessor are considered
read-only. In our example, FullName is a read-only property.
2. Write-Only Properties: Properties without a get accessor are considered
write-only. In our example, the Country is a write-only property.
3. Read-Write Properties: Properties with both a get and set accessor are
considered read-write properties. In our example, FirstName and LastName
are read-write properties.
What are the advantages of using properties in C#?
1. Properties can validate data before allowing a change.
2. It can transparently expose data on a class where that data is actually
retrieved from some other source such as a database.
3. Properties can take action when data is changed, such as raising an event
or changing the value of other fields.
What is a static property? Give an example.
A property that is marked with a static keyword is considered a static property. This makes
the property available to callers at any time, even if no instance of the class exists. In the
example below PI is a static property.
get
return _firstName;
set
_firstName = value;
}
get
return _lastName;
set
_lastName = value;
// FullName is virtual
get
get
class MainClass
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
}
What is an Abstract Property in C#? Give an example.
A property that is marked with the abstract keyword is considered abstract property. An
abstract property should not have any implementation in the class. The derived classes
must write their own implementation. In the example below FullName property is abstract
in the Customer class. BankCustomer class overrides the inherited abstract FullName
property with its own implementation.
using System;
get
return _firstName;
set
_firstName = value;
get
return _lastName;
set
_lastName = value;
// FullName is abstract
get;
get
class MainClass
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
}
Can you use virtual, override, or abstract keywords on an accessor of
a static property?
No, it is a compile-time error to use virtual, abstract, or override keywords on an accessor
of a static property.
Is C# a strongly-typed language?
Yes
What are the 2 broad classifications of data types available in C#?
1. Built-in data types.
2. User-defined data types.
Give some examples of built-in data types in C#.
1. Int
2. Float
3. Bool
How do you create user-defined data types in C#?
You use the struct, class, interface, and enum constructs to create your own custom types.
The .NET Framework class library itself is a collection of custom types provided by
Microsoft that you can use in your own applications.
Difference between int and Int32 in C#
This is one of the frequently asked C# Interview Questions and
Answers. Int32 and int are synonymous, both of them allow us to create a 32-bit integer.
int is shorthand notation (alias) for Int32. When declaring an integer in a c# program most
of us prefer using int over Int32. Whether we use int or Int32 to create an integer, the
behavior is identical.
I think the only place where Int32 is not allowed is when creating an enum. The following
code will raise a compiler error stating – Type byte, sbyte, short, ushort, int, uint, long,
or ulong expected.
enum Test : Int32
abc = 1
}
The following code will compile just fine
enum Test: int
abc = 1
}
I can think of only the following minor differences between int and Int32
1. One of the differences is in readability. When we use Int32, we are being
explicit about the size of the variable.
2. To use Int32, either we need to use using System declaration or specify
the fully qualified name (System.Int32) whereas with int it is not required.
What are the 2 types of data types available in C#?
1. Value Types
2. Reference Types
If you define a user-defined data type by using the struct keyword, Is it
a value type or reference type?
Value Type
If you define a user-defined data type by using the class keyword, Is it
a value type or reference type?
Reference type
Are Value types sealed?
Yes, Value types are sealed.
What is the base class from which all value types are derived?
System.ValueType
Give examples of value types.
1. Enum
2. Struct
Give examples for reference types.
1. Class
2. Delegate
3. Array
4. Interface
What are the differences between value types and reference types?
This is one of the frequently asked C# Interview Questions and Answers. Value types are
stored on the stack whereas reference types are stored on the managed heap. The Value
type variables directly contain their values whereas reference variables hold only a
reference to the location of the object that is created on the managed heap.
There is no heap allocation or garbage collection overhead for value-type variables. As
reference types are stored on the managed heap, they have the overhead of object
allocation and garbage collection.
Value Types cannot inherit from another class or struct. Value types can only inherit from
interfaces. Reference types can inherit from another class or interface.
My understanding is that just because structs inherit from System.ValueType, cannot
inherit from another class, because we cannot do multiple-class inheritance.
Structs can inherit from System.ValueType class but cannot be inherited by any other
types like Structs or Class. In other words, Structs are like Sealed classes that cannot be
inherited.
What do you mean by casting a data type?
Converting a variable of one data type to another data type is called casting. This is also
called data type conversion.
What are the 2 kinds of data type conversions available in C#?
Implicit conversions: No special syntax is required because the conversion is typesafe
and no data will be lost. Examples include conversions from smaller to larger integral types
and conversions from derived classes to base classes.
Explicit conversions: Explicit conversions require a cast operator. The source and
destination variables are compatible, but there is a risk of data loss because the type of
the destination variable is a smaller size than (or is a base class of) the source variable.
What is the difference between an implicit conversion and an explicit
conversion?
Explicit conversions require a cast operator whereas an implicit conversion is done
automatically. The Explicit conversion can lead to data loss whereas with implicit
conversions there is no data loss.
What type of data type conversion happens when the compiler
encounters the following code?
ChildClass CC = new ChildClass();
ParentClass PC = new ParentClass();
Implicit Conversion: For reference types, an implicit conversion always exists from a
class to any one of its direct or indirect base classes or interfaces. No special syntax is
necessary because a derived class always contains all the members of a base class.
Will the following code compile?
double d = 9999.11;
int i = d;
No, the above code will not compile. Double is a larger data type than an integer. An
implicit conversion is not done automatically because there is a data loss. Hence we have
to use explicit conversion as shown below.
double d = 9999.11;
int i = (int)d; //Cast double to int.
If you want to convert a base type to a derived type, what type of
conversion do you use?
Explicit conversion is as follows. Create a new derived type.
Car C1 = new Car();
Implicit conversion to the base type is safe.
Vehicle V = C1;
Advertisements
Explicit conversion is required to cast back to the derived type. The code below will
compile but throw an exception at runtime if the right-side object is not a Car object.
Car C2 = (Car) V;
What operators can be used to cast from one reference type to another
without the risk of throwing an exception?
The is and as operators can be used to cast from one reference type to another without
the risk of throwing an exception.
If casting fails what type of exception is thrown?
InvalidCastException
What is the difference between int.Parse and int.TryParse methods?
This is one of the frequently asked C# Interview Questions and Answers. The parse
method throws an exception if the string you are trying to parse is not a valid number
whereas TryParse returns false and does not throw an exception if parsing fails. Hence
TryParse is more efficient than Parse.
What are Boxing and Unboxing?
Boxing – Converting a value type to a reference type is called boxing. An example is
shown below.
int i = 101;
object obj = (object)i; // Boxing
Unboxing – Converting a reference type to a value type is called unboxing. An example
is shown below.
obj = 101;
i = (int)obj; // Unboxing
Is boxing an implicit conversion?
Yes, boxing happens implicitly.
Is unboxing an implicit conversion?
No, unboxing is an explicit conversion.
What happens during the process of boxing?
This is one of the frequently asked C# Interview Questions and Answers. Boxing is used
to store value types in the garbage-collected heap. Boxing is an implicit conversion of a
value type to the type object or to any interface type implemented by this value type.
Boxing a value type allocates an object instance on the heap and copies the value into
the new object. Due to this boxing and unboxing can have a performance impact.
What are Access Modifiers in C#?
This is one of the frequently asked C# Interview Questions and Answers. In C# there are
5 different types of Access Modifiers.
1. Public: The public type or member can be accessed by any other code in
the same assembly or another assembly that references it.
2. Private: The type or member can only be accessed by code in the same
class or struct.
3. Protected: The type or member can only be accessed by code in the same
class or struct, or in a derived class.
4. Internal: The type or member can be accessed by any code in the same
assembly, but not from another assembly.
5. Protected Internal: The type or member can be accessed by any code in the
same assembly, or by any derived class in another assembly.
What are Access Modifiers used for?
Access Modifiers are used to control the accessibility of types and members within the
types.
Can we use all access modifiers for all types?
No, not all access modifiers can be used by all types of members in all contexts, and in
some cases, the accessibility of a type member is constrained by the accessibility of its
containing type.
Can derived classes have greater accessibility than their base types?
No, Derived classes cannot have greater accessibility than their base types. For example,
the following code is illegal.
When we compile the above code an error will be generated stating “Inconsistent
accessibility: base class InternalBaseClass is less accessible than class
PublicDerivedClass“. To make this simple, you cannot have a public
class PublicDerivedClass that derives from an internal class InternalBaseClass. If this
were allowed, it would have the effect of making public, because all protected or internal
members of A are accessible from the derived class.
Is the following code legal in C#?
private class Test
{
}
}
No, a compile-time error will be generated stating “Namespace elements cannot be
explicitly declared as private, protected, or protected internal“
Can you declare struct members as protected?
No, struct members cannot be declared protected. This is because structs do not support
inheritance.
Can the accessibility of a type member be greater than the
accessibility of its containing type?
No, the accessibility of a type member can never be greater than the accessibility of its
containing type. For example, a public method declared in an internal class has only
internal accessibility.
Can destructors have access modifiers?
No, destructors cannot have access modifiers.
What do protected internal access modifiers mean?
The protected internal access means protected OR internal, not protected, AND internal.
In simple terms, a protected internal member is accessible from any class in the same
assembly, including derived classes. To limit access to only derived classes in the same
assembly, declare the class itself internal, and declare its members as protected.
What is the default access modifier for a class, struct, and interface declared
directly with a namespace?
internal
Will the following code compile in C#?
interface IInterface
}
No, you cannot specify the access modifier for an interface member. Interface members
are always public.
Can you specify an access modifier for an enumeration?
Enumeration members are always public, and no access modifiers can be specified.
Inheritance and Interface Interview Questions in C#
}
No, a child class can have only one base class. We cannot specify 2 base classes at the
same time. C# supports single class inheritance only. Therefore, we can specify only one
base class to inherit from. However, it does allow multiple interface inheritance.
Does C# support multiple class inheritance?
No, C# supports single class inheritance only. However, classes can implement multiple
interfaces at the same time.
Why does C# not support multiple class inheritance?
C# does not support multiple class inheritance because of the diamond problem that is
associated, with multiple class inheritance. Let us understand the diamond problem of
multiple class inheritance with an example.
As shown in the image above, I have 2 classes – Class B and Class C and Both of these
classes are inherited from Class A. Now, we have another class i.e. Class D which is
inherited from both Class B and Class C
So if a method in Class D calls a method defined in Class A and Class D has not
overridden the invoked method. But both Class B and Class C have overridden the same
method differently. Now, the ambiguity is, from which class does, Class D inherits the
invoked method: Class B, or Class C?
Advertisements
In order not to have these problems, C# does not support multiple class inheritance.
What is the difference between interfaces and abstract classes?
There are several differences between an abstract class and an interface as listed below.
1. Abstract classes can have implementations for some of their members,
but the interface can’t have the implementation for any of its members.
2. Interfaces cannot have fields where an abstract class can have fields.
3. An interface can inherit from another interface only and cannot inherit
from an abstract class whereas an abstract class can inherit from another
abstract class or another interface.
4. A class can inherit from multiple interfaces at the same time, whereas a
class cannot inherit from multiple abstract classes at the same time.
5. Abstract class members can have access modifiers where as interface
members cannot have access modifiers as they are by default public.
When do you choose interface over an abstract class or vice versa?
If we have an implementation (function with the body) that will be the same for all the
derived classes, then it is better to go for an abstract class instead of an interface. When
we have an interface, we can move our implementation to any class that implements the
interface. Whereas, when we have an abstract class, we can share implementation for all
derived classes in one central place, and avoid code duplication in derived classes.
What are the advantages of using interfaces?
This is the most commonly asked interview question. This interview question is being
asked in almost all the dot net interviews. It is very important that we understand all the
concepts of interfaces and abstract classes. Interfaces are very powerful. If properly
used, interfaces provide all the advantages as listed below.
1. Interfaces allow us to implement polymorphic behavior. Of course,
abstract classes can also be used to implement polymorphic behavior.
2. The Interfaces allow us to develop very loosely coupled systems.
3. Interfaces enable mocking for better unit testing.
4. The Interfaces enable us to implement multiple inheritances in C#.
5. Interfaces are great for implementing Inversion of Control or Dependency
Injection.
6. The Interfaces enable parallel application development.
Can an Interface contain fields?
No, an Interface cannot contain fields
What is the difference between class inheritance and interface
inheritance?
Classes and structs can inherit from interfaces just like how classes can inherit a base
class or struct. However, there are 2 differences.
A class or a struct can inherit from more than one interface at the same time whereas a
class or a struct cannot inherit from more than one class at the same time
When a class or struct inherits an interface, it inherits only the method names and
signatures, because the interface itself contains no implementations.
Can an interface inherit from another interface?
Yes, an interface can inherit from another interface. It is possible for a class to inherit an
interface multiple times, through base classes or interfaces it inherits. In this case, the
class can only implement the interface one time, if it is declared as part of the new class.
If the inherited interface is not declared as part of the new class, its implementation is
provided by the base class that declared it. It is possible for a base class to implement
interface members using virtual members; in that case, the class inheriting the interface
can change the interface behavior by overriding the virtual members.
Can you create an instance of an interface?
No, we cannot create an instance of an interface.
If a class inherits an interface, what are the 2 options available for that
class?
Option1: Provide Implementation for all the members, inherited from the interface.
Option2: If the class does not wish to provide Implementation for all the members
inherited from the interface, then the class has to be marked as abstract.
What do you mean by “Explicitly Implementing an Interface”? Give an
example?
If a class is implementing the inherited interface member by prefixing the name of the
interface, then the class is “Explicitly Implementing an Interface member”. The
disadvantage of Explicitly Implementing an Interface member is that the class object has
to be typecasted to the interface type to invoke the interface member. An example is
shown below.
namespace Interfaces
interface Car
void Drive();
}
void Car.Drive()
Console.WriteLine("Drive Car");
//DemoObject.Drive();
((Car)DemoObject).Drive();
}
When to use Interface?
If your child classes should implement a certain group of methods/functionalities but each
of the child classes is free to provide its own implementation then use interfaces.
Why should the method have an abstract keyword if it does not have
the body?
In a class, we are allowed only to define a class with the body. Since we are changing its
default property (which means removing its body) it must have the abstract keyword in its
prototype.
What are the characteristics of an abstract class in C#?
1. The abstract class can contain both abstract methods and non-abstract
(concrete) methods.
2. It can contain both static and instance variables.
3. The abstract class cannot be instantiated but its reference can be created.
4. If any class contains abstract methods then it must be declared by using
the keyword abstract.
}
}
((BaseClass)DC).Method();
}
What is the difference between a virtual method and an abstract
method?
This is one of the frequently asked C# Polymorphism interview questions. A virtual method
must have a body whereas an abstract method should not have a body. A Base class
virtual method may or may not be overridden in the Derived class whereas a Base class
Abstract method has to be implemented by the derived class.
Delegate Interview Questions and Answers in C#
In this article, I am going to discuss the most frequently asked Delegate Interview
Questions and Answers in C#. Please read our previous article where we discussed the
most frequently asked Functions. Fields, and Constants Interview Questions in
C# with Answers. As part of this article, we are going to discuss the following Delegates
Interview Questions and Answers in C#.
Advertisements
The signature of the delegate must match with the signature of the function, the delegate
points to otherwise we will get a compiler error. This is the reason delegates are called
type-safe function pointers.
A Delegate is similar to a class. We can create an instance of it and when we do so, we
pass the function name as a parameter to the delegate constructor, and it is the function
name that the delegate points to.
Advertisements
del4();
Console.WriteLine("SampleMethodOne Invoked");
Console.WriteLine("SampleMethodTwo Invoked");
{
Console.WriteLine("SampleMethodThree Invoked");
}
Approach2:
namespace Sample
del += SampleMethodTwo;
del += SampleMethodThree;
del -= SampleMethodTwo;
del();
Console.WriteLine("SampleMethodOne Invoked");
{
Console.WriteLine("SampleMethodTwo Invoked");
Console.WriteLine("SampleMethodThree Invoked");
}
Note: A multicast delegate invokes the methods in the invocation list, in the same order
in which they are added.
If the delegate has a return type other than void and if the delegate is a multicast delegate,
only the value of the last invoked method will be returned. Along the same lines, if the
delegate has an out parameter, the value of the output parameter will be the value
assigned by the last method.
Where do you use multicast delegates?
Multicast delegate makes the implementation of the observer design pattern very simple.
The observer pattern is also called a publish/subscribe pattern.
Where did you use delegates in your project? Or how did you use
delegates in your project?
The Delegate is one of the very important aspects to understand. Most of the interviewers
ask you to explain the usage of delegates in a real-time project that you have worked
on. Delegates are extensively used by framework developers. Let us say we have a class
called Employee as shown below.
Employee Class
public class Employee
}
The Employee class has the following properties.
1. Id
2. Name
3. Experience
4. Salary
Now I want to write a method in the Employee class which can be used to promote
employees. The method should take a list of Employee objects as a parameter and should
print the names of all the employees who are eligible for a promotion. But the logic based
on which the employee gets promoted should not be hardcoded. At times we may promote
employees based on their experience and at times we may promote them based on their
salary or maybe some other condition. So, the logic to promote employees should not be
hard-coded within the method.
How to achieve?
To achieve this we can make use of delegates. So now I would design my class as shown
below. We also created a delegate EligibleToPromotion. This delegate takes the
Employee object as a parameter and returns a boolean. In the Employee class, we have
the PromoteEmpoloyee method. This method takes a list of Employees and a Delegate of
the type EligibleToPromotion as parameters. The method then loops through each
employee object and passes it to the delegate. If the delegate returns true, then the
Employee is promoted, else not promoted. So within the method, we have not hardcoded
any logic on how we want to promote employees.
namespace DelegateDemo
if (IsEmployeeEligible(employee))
}
So now the client who uses the Employee class has the flexibility of determining the logic
on how they want to promote their employees as shown below. First create the employee
objects – E1, E2, and E3. Populate the properties for the respective objects. We then
create an employeeList to hold all the 3 employees.
Notice the Promote method that we have created. This method has the logic of how we
want to promote our employees. The method is then passed as a parameter to the
delegate. Also, note this method has the same signature as that of the
EligibleToPromotion delegate. This is very important because the Promote method cannot
be passed as a parameter to the delegate if the signature differs. This is the reason why
delegates are called type-safe function pointers.
namespace DelegateDemo
if (IsEmployeeEligible(employee))
class Program
ID = 101,
Name = "Pranaya",
Experience = 5,
Salary = 10000
};
ID = 102,
Name = "Kumar",
Experience = 10,
Salary = 20000
};
ID = 103,
Name = "Rout",
Experience = 20,
Salary = 30000
};
lstEmployess.Add(emp1);
lstEmployess.Add(emp2);
lstEmployess.Add(emp3);
Employee.PromoteEmployee(lstEmployess, eligibleTopromote);
Console.ReadKey();
return true;
else
return false;
}
So if we did not have the concept of delegates it would not have been possible to pass a
function as a parameter. As the Promote method in the Employee class makes use of
delegate, it is possible to dynamically decide the logic on how we want to promote
employees.
Using Lambda expressions
In C Sharp 3.0 Lambda expressions are introduced. So you can make use of lambda
expressions instead of creating a function and then an instance of a delegate and then
passing the function as a parameter to the delegate. The sample example rewritten using
the Lambda expression is shown below. The private Promote method is no longer required
now.
class Program
ID = 101,
Name = "Pranaya",
Experience = 5,
Salary = 10000
};
ID = 102,
Name = "Kumar",
Experience = 10,
Salary = 20000
};
ID = 103,
Name = "Rout",
Experience = 20,
Salary = 30000
};
lstEmployess.Add(emp1);
lstEmployess.Add(emp2);
lstEmployess.Add(emp3);
What is Destructor?
A Destructor has the same name as the class with a tilde character and is used to destroy
an instance of a class.
Can a class have more than 1 destructor?
No, a class can have only 1 destructor.
Can structs in C# have destructors?
No, structs can have constructors but not destructors, only classes can have destructors.
Can you pass parameters to destructors?
No, you cannot pass parameters to destructors. Hence, you cannot overload destructors.
Can you explicitly call a destructor?
No, you cannot explicitly call a destructor. Destructors are invoked automatically by the
garbage collector.
Why is it not a good idea to use Empty destructors?
When a class contains a destructor, an entry is created in the Finalize queue. When the
destructor is called, the garbage collector is invoked to process the queue. If the destructor
is empty, this just causes a needless loss of performance.
Is it possible to force the garbage collector to run?
Yes, it possible to force the garbage collector to run by calling the Collect() method, but
this is not considered a good practice because this might create a performance overhead.
Usually, the programmer has no control over when the garbage collector runs. The
garbage collector checks for objects that are no longer being used by the application. If it
considers an object eligible for destruction, it calls the destructor(if there is one) and
reclaims the memory used to store the object.
Usually, in .NET, the CLR takes care of memory management. Is there any need for
a programmer to explicitly release memory and resources? If yes, why and how?
If the application is using an expensive external resource, it is recommended to explicitly
releasing the resource before the garbage collector runs and frees the object. We can do
this by implementing the Dispose method from the IDisposable interface that performs the
necessary cleanup for the object. This can considerably improve the performance of the
application.
When do we generally use destructors to release resources?
If the application uses unmanaged resources such as windows, files, and network
connections, we use destructors to release resources.
When to use a Private constructor in c#?
This is one of the frequently asked Constructor Interview Questions in C#.
There are several reasons for using private constructors
1. When we want the caller of the class only to use the class but not
instantiate.
2. If you want to ensure a class can have only one instance at a given time,
i.e. private constructors are used in implementing Singleton() design
pattern.
3. When a class has several overloads of the constructor, and some of them
should only be used by the other constructors and not external code.
Multithreading and Deadlock Interview Questions
and Answers in C#
In this article, I am going to discuss the most frequently asked Multithreading and
Deadlock Interview Questions and Answers in C#. Please read our previous article
where we discussed the most frequently asked Delegates Interview Questions in
C# with Answers. As part of this article, we are going to discuss the following
Multithreading and Deadlock Interview Questions and Answers in C#.
1. What are the Thread and Process?
2. What is the difference between Process and Thread?
3. Why do we need Multi-threading in our project?
4. What are the advantages and disadvantages of multithreading in
C#?
5. How can we create a Thread in C#?
6. Why does a delegate need to be passed as a parameter to the
Thread class constructor?
7. How to pass parameter in Thread?
8. Why do we need a ParameterizedThreadStart delegate?
9. When to use ParameterizedThreadStart over ThreadStart delegate?
10. How to pass data to the thread function in a type-safe manner?
11. How to retrieve the data from a thread function?
12. What is the difference between Threads and Tasks?
13. What is the Significance of Thread.Join and Thread.IsAlive
functions in multithreading?
14. What happens if shared resources are not protected from
concurrent access in a multithreaded program?
15. How do protect shared resources from concurrent access?
16. What are the Interlocked functions?
17. What is a Lock?
18. What is the Difference between Monitor and lock in C#?
19. Explain why and how a deadlock can occur in multithreading with an
example?
20. How to resolve a deadlock in a multithreaded program?
21. What is AutoResetEvent and how it is different from
ManualResetEvent?
22. What is the Semaphore?
23. Explain Mutex and how it is different from other Synchronization
mechanisms?
24. What is the Race condition?
25. How can you share data between multiple threads?
26. What are Concurrent Collection Classes?
27. What is synchronization and why it is important?
28. Explain the four necessary conditions for Deadlock?
29. What is LiveLock?
What are the Thread and Process?
Process – Process is something that the operating system uses to execute a program by
providing the resources required. Each process has a unique process id associated with
it. We can view the process within which a program is running using the windows task
manager.
Thread – A Thread is a lightweight process that is responsible for executing application
code. A process has at least one thread which is commonly called the main thread which
actually executes the application code. A single process can have multiple threads.
Every application by default contains one thread to execute the program and that thread
is known as the main thread. So every program by default is a single-threaded model.
What is the difference between Process and Thread?
This is one of the most frequently asked Multithreading Interview Questions in C#. A
process is started when you start an Application. The process is a collection of resources
like virtual address space, code, security contexts, etc. A process can start multiple
threads. Every process starts with a single thread called the primary thread. You can
create n number of threads in a process. Threads share the resources allocated to the
process. A process is the parent and threads are his children.
Why do we need Multi-threading in our project?
This is one of the most frequently asked Multithreading Interview Questions in C#.NET.
Let us discuss this question. Multi-threading is used to run multiple threads
simultaneously. Some main advantages are:
1. You can do multiple tasks simultaneously. For e.g. saving the details of
the user to a file while at the same time retrieving something from a web
service.
2. Threads are much more lightweight than processes. They don’t get their
own resources. They used the resources allocated to a process.
3. Context-switch between threads takes less time than process.
What are the advantages and disadvantages of multithreading?
I think this MultiThreading Interview Question is the most asked interview question in the
dot net. So let us discuss the advantages and disadvantages
Advantages of multithreading:
1. To maintain a responsive user interface
2. It makes efficient use of processor time while waiting for I/O operations to
complete.
3. To split large, CPU-bound tasks to be processed simultaneously on a
machine that has multiple CPUs/cores.
Disadvantages of multithreading:
1. On a single-core/processor machine threading can affect performance
negatively as there is overhead involved with context-switching.
2. Have to write more lines of code to accomplish the same task.
3. Multithreaded applications are difficult to write, understand, debug, and
maintain.
Please Note: Only use multithreading when the advantages of doing so outweigh the
disadvantages.
How can we create a Thread in C#?
To create a THREAD, we need to create an instance of Thread class (Thread class
provided by System.Threading namespace) and to its constructor, we have to pass the
function name as a parameter that we want the thread to execute. Then we need to call
the start method of the Thread class.
Let us understand this with an example as shown below.
In the above example, the following statement does the same
Thread T1 = new Thread(Number.PrintNumbers); T1.Start();
We can rewrite the above line using the ThreadStart delegate as shown below.
Thread T1 = new Thread(new ThreadStart(Number.PrintNumbers));
T1.Start();
Why does a delegate need to be passed as a parameter to the Thread
class constructor?
As we know the purpose of creating a Thread is to execute a function. We also know that
a delegate is a type-safe function pointer meaning it points to a function that the thread
has to execute. In short, all threads require an entry point to start execution. Any thread
that we create will need an explicitly defined entry point i.e. a pointer to the function from
where they should begin execution. So threads always require a delegate.
In the code below, we are not explicitly creating the ThreadStart delegate, then how
is it working here?
Thread T1 = new Thread(Number.PrintNumbers);
It’s working in spite of not creating the ThreadStart delegate explicitly because the
framework is doing it automatically for us. We can also rewrite the same line using the
delegate() keyword as shown below.
Thread T1 = new Thread(delegate() { Number.PrintNumbers(); });
We can also rewrite the same line using the lambda expression as shown below.
Thread T1 = new Thread(() => Number.PrintNumbers());
How to pass the parameter in Thread?
In the constructor of Thread, we can pass the method name which accepts only a single
parameter. Then we have to pass the parameter into the Start method.
Why do we need a ParameterizedThreadStart delegate?
When we need to pass data to the thread function then in such situations we need to use
the ParameterizedThreadStart delegate. Here is an example that shows the usage of a
ParameterizedThreadStart delegate.
namespace MultithreadingDemo
{
class Program
{
public static void Main()
{
Console.WriteLine("Please enter the target number");
object target = Console.ReadLine();
// Create an instance of ParameterizedThreadStart delegate
ParameterizedThreadStart parameterizedThreadStart =
new ParameterizedThreadStart(Number.PrintNumbers);
Thread T1 = new Thread(parameterizedThreadStart);
// Pass the traget number to the start function, which
// will then be passed automatically to PrintNumbers() function
T1.Start(target);
}
}
class Number
{
public static void PrintNumbers(object target)
{
int number = 0;
if (int.TryParse(target.ToString(), out number))
{
for (int i = 1; i <= number; i++)
{
Console.WriteLine(i);
}
}
}
}
}
The code in the Main() function can also be written as shown below.
public static void Main()
{
Console.WriteLine("Please enter the target number");
object target = Console.ReadLine();
Thread T1 = new Thread(Number.PrintNumbers);
T1.Start(target);
}
In the above example, we are not explicitly creating an instance of the
ParameterizedThreadStart delegate. Then how is it working?
It’s working because the compiler implicitly
converts new Thread(Number.PrintNumbers) to
new Thread(new ParameterizedThreadStart(Number.PrintNumbers));
When to use ParameterizedThreadStart over ThreadStart delegate?
We need to use the ParameterizedThreadStart delegate if we have some data to pass to
the Thread function, otherwise, just use the ThreadStart delegate.
Please note: Using ParameterizedThreadStart delegate and Thread.Start(Object)
method to pass data to the Thread function is not type-safe as they operate on object
datatype and any type of data can be passed. In the above, If we try to change the data
type of the target parameter of the PrintNumbers() function from object to int, a compiler
error will be raised as the signature of the PrintNumbers() function does not match with
the signature of ParameterizedThreadStart delegate.
How to pass data to the thread function in a type-safe manner?
This MultiThreading Interview Question in C# can be asked in almost all interviews. To
pass data to the Thread function in a type-safe manner, encapsulate the thread function
and the data it needs in a helper class and use the ThreadStart delegate to execute the
thread function. An example is shown below.
namespace ThreadingExample
{
class Program
{
public static void Main()
{
// Prompt the user for the target number
Console.WriteLine("Please enter the target number");
// Read from the console and store it in target variable
int target = Convert.ToInt32(Console.ReadLine());
// Create an instance of the Number class, passing it
// the target number that was read from the console
Number number = new Number(target);
// Specify the Thread function
Thread T1 = new Thread(new ThreadStart(number.PrintNumbers));
// Alternatively we can just use Thread class constructor as shown below
// Thread T1 = new Thread(number.PrintNumbers);
T1.Start();
}
}
// Number class also contains the data it needs to print the numbers
class Number
{
int _target;
// When an instance is created, the target number needs to be specified
public Number(int target)
{
// The targer number is then stored in the class private variable _target
this._target = target;
}
// Function prints the numbers from 1 to the traget number that the user provided
public void PrintNumbers()
{
for (int i = 1; i <= _target; i++)
{
Console.WriteLine(i);
}
}
}
}
How to retrieve the data from a thread function?
Retrieving data from the Thread function using the callback method.
namespace ThreadStartDelegateExample
{
// Step 1: Create a callback delegate. The actual callback method
// signature should match with the signature of this delegate.
public delegate void SumOfNumbersCallback(int sumOfNumbers);
// Step 2: Create Number class to compute the sum of numbers and
// to call the callback method
class Number
{
// The traget number this class needs to compute the sum of numbers
int _target;
// Delegate to call when the the Thread function completes
// computing the sum of numbers
SumOfNumbersCallback _callbackMethod;
// Constructor to initialize the target number and the callback delegateinitialize
public Number(int target, SumOfNumbersCallback callbackMethod)
{
this._target = target;
this._callbackMethod = callbackMethod;
}
// This thread function computes the sum of numbers and then invokes
// the callback method passing it the sum of numbers
public void ComputeSumOfNumbers()
{
int sum = 0;
for (int i = 1; i <= _target; i++)
{
sum = sum + i;
}
if (_callbackMethod != null)
{
_callbackMethod(sum);
}
}
}
// Step 3: This class consumes the Number class created in Step 2
class Program
{
// Callback method that will receive the sum of numbers
public static void PrintSumOfNumbers(int sum)
{
Console.WriteLine("Sum of numbers is " + sum);
}
public static void Main()
{
// Prompt the user for the target number
Console.WriteLine("Please enter the target number");
// Read from the console and store it in target variable
int target = Convert.ToInt32(Console.ReadLine());
// Create an instance of callback delegate and to it's constructor
// pass the name of the callback function (PrintSumOfNumbers)
SumOfNumbersCallback callbackMethod =
newSumOfNumbersCallback(PrintSumOfNumbers);
// Create an instance of Number class and to it's constrcutor pass the target
// number and the instance of callback delegate
Number number = new Number(target, callbackMethod);
// Create an instance of Thread class and specify the Thread function to invoke
Thread T1 = new Thread(new ThreadStart(number.ComputeSumOfNumbers));
T1.Start();
}
}
}
What is the difference between Threads and Tasks?
This is one of the most frequently asked Multithreading Interview Questions in C#. Let us
understand the differences between them.
1. Tasks are the wrapper around Thread and ThreadPool classes. Below are
some major differences between Threads and Tasks:
2. A Task can return a result but there is no proper way to return a result
from Thread.
3. We can apply chaining to multiple tasks but we cannot in threads.
4. We can wait for Tasks without using Signalling. But in Threads, we have
to use event signals like AutoResetEvent and ManualResetEvent.
5. We can apply the Parent/Child relationship in Tasks. A Task at one time
becomes a parent of multiple tasks. Parent Tasks does not completed until
their child’s tasks are completed. We do not have any such mechanism in
the Thread class.
6. Child Tasks can propagate their exceptions to the parent Task and All
child exceptions are available in the AggregateException class.
7. Task has an in-build cancellation mechanism using the CancellationToken
class.
What is the Significance of Thread.Join and Thread.IsAlive functions in
multithreading?
This is one of the most frequently asked Multithreading Interview Questions in C#. Join
blocks the current thread and makes it wait until the thread on which the Join method is
invoked completes. The join method also has an overload where we can specify the
timeout. If we don’t specify the timeout the calling thread waits indefinitely, until the thread
on which Join() is invoked completes. This overloaded Join (int millisecondsTimeout)
method returns a boolean true if the thread has terminated otherwise false. Join is
particularly useful when we need to wait and collect results from a thread execution or if
we need to do some cleanup after the thread has been completed.
The IsAlive returns boolean True if the thread is still executing otherwise false.
Program code used in the demo:
namespace MultithreadingDemo
{
class Program
{
public static void Main()
{
Console.WriteLine("Main Thread Started" + Thread.CurrentThread.Name);
Thread T1 = new Thread(Program.Thread1Function);
T1.Start();
Thread T2 = new Thread(Program.Thread2Function);
T2.Start();
//if (T1.Join(1000))
//{
// Console.WriteLine("Thread1Function completed");
//}
//else
//{
// Console.WriteLine("Thread1Function hot not completed in 1 second");
//}
T1.Join();
T2.Join();
Console.WriteLine("Thread2Function completed");
for (int i = 1; i <= 10; i++)
{
if (T1.IsAlive)
{
Console.WriteLine("Thread1Function is still doing it's work");
Thread.Sleep(500);
}
else
{
Console.WriteLine("Thread1Function Completed");
break;
}
}
Console.WriteLine("Main Thread Completed");
Console.ReadLine();
}
public static void Thread1Function()
{
Console.WriteLine("Thread1Function started");
Thread.Sleep(5000);
Console.WriteLine("Thread1Function is about to return");
}
public static void Thread2Function()
{
Console.WriteLine("Thread2Function started");
}
}
}
What happens if shared resources are not protected from concurrent
access in a multithreaded program?
This is one of the most frequently asked Multithreading Interview Questions in
C#.NET. The output or behavior of the program can become inconsistent. Let us
understand this with an example.
namespace MultithreadingDemo
{
class Program
{
static int Total = 0;
public static void Main()
{
AddOneMillion();
AddOneMillion();
AddOneMillion();
Console.WriteLine("Total = " + Total);
Console.ReadLine();
}
public static void AddOneMillion()
{
for (int i = 1; i <= 1000000; i++)
{
Total++;
}
}
}
}
Output: Total = 3000000
The above program is a single-threaded program. In the Main()
method, AddOneMillion() method is called 3 times, and it updates the Total field correctly
as expected, and finally prints the correct total i.e. 3000000.
Now, let’s rewrite the program using multiple threads.
namespace MultithreadingDemo
{
class Program
{
static int Total = 0;
public static void Main()
{
Thread thread1 = new Thread(Program.AddOneMillion);
Thread thread2 = new Thread(Program.AddOneMillion);
Thread thread3 = new Thread(Program.AddOneMillion);
thread1.Start();
thread2.Start();
thread3.Start();
thread1.Join();
thread2.Join();
thread3.Join();
Console.WriteLine("Total = " + Total);
Console.ReadLine();
}
public static void AddOneMillion()
{
for (int i = 1; i <= 1000000; i++)
{
Total++;
}
}
}
}
Every time we run the above program, we get a different output. The inconsistent output
is because the Total field which is a shared resource is not protected from concurrent
access by multiple threads. The operator ++ is not thread-safe.
How do protect shared resources from concurrent access?
This Multithreading Interview Question is asked in almost all interviews. So let’s discuss
this in detail. There are several ways to protect shared resources from concurrent access.
Let’s explore 2 of the options.
Using Interlocked.Increment() method: Modify AddOneMillion() method as shown
below. The Interlocked.Increment() Method, increments a specified variable and stores
the result, as an atomic operation
public static void AddOneMillion()
{
for (int i = 1; i <= 1000000; i++)
{
Interlocked.Increment(ref Total);
}
}
The other option is to use a lock.
static object _lock = new object();
public static void AddOneMillion()
{
for (int i = 1; i <= 1000000; i++)
{
lock (_lock)
{
Total++;
}
}
}
Which option is better?
From a performance perspective using the Interlocked class is better than using
locking. Locking locks out all the other threads except a single thread to read and
increment the Total variable. This will ensure that the Total variable is updated safely. The
downside is that since all the other threads are locked out, there is a performance hit.
The Interlocked class can be used with addition/subtraction (increment, decrement, add,
etc.) on an int or long field. The Interlocked class has methods for incrementing,
decrementing, adding, and reading variables atomically.
The following code prints the time taken in ticks. 1 millisecond consists of 10000 ticks.
public static void Main()
{
Stopwatch stopwatch = Stopwatch.StartNew();
Thread thread1 = new Thread(Program.AddOneMillion);
Thread thread2 = new Thread(Program.AddOneMillion);
Thread thread3 = new Thread(Program.AddOneMillion);
thread1.Start();
thread2.Start();
thread3.Start();
thread1.Join();
thread2.Join();
thread3.Join();
Console.WriteLine("Total = " + Total);
stopwatch.Stop();
Console.WriteLine("Time Taken in Ticks = " + stopwatch.ElapsedTicks);
}
Please Note: You can use the TimeSpan object to find ticks per second, ticks per
millisecond, etc. Stopwatch class is in System.Diagnostics namespace.
What are the Interlocked functions?
Interlocked functions in .NET are useful in multithreading programs to safely change the
value of shared variables. By default, C# variables are not thread-safe. When we apply
addition, subtraction, or checking the value of variables multiple threads can corrupt the
variables. For preventing these dirty reads, we can use Interlocked functions.
Interlocked functions can only work on int, long, double, and float data types
What is a Lock?
The Lock is another synchronization mechanism in C# and one of the famous multi-
threading interview questions in .NET. It restricts the critical region so that only one thread
can enter a critical region at a time.
The lock needs an object to continue its operation. It applies a lock on a target object and
only one thread can lock that target object at a time
What is the Difference between Monitor and lock in C#?
I think you need to be prepared for this Multithreading Interview Questions and
Answer if you are preparing to attend the interview questions on Multithreading. So let us
discuss this question in detail
1. The Lock is just a shortcut for the Monitor statement. Compiler internally
converts lock statement to Monitor.Enter and Exit statements.
2. Monitor class provides some useful method which is not in the lock
statement. These methods are very useful in advanced scenarios.
3. The monitor provides the TryEnter method. This method is useful when
we need to provide a timeout value.
4. TryEnter is also useful when we have to check whether the lock is taken
or not. We can pass a boolean parameter that returns true if the lock is
taken else returns false.
5. The Pulse method notifies a waiting thread of a change in the locked
object’s state.
6. The Wait method releases the current acquired lock and blocks the
current thread until it reacquires the lock.
Both Monitor class and lock provide a mechanism to protect the shared resources in a
multithreaded application. The lock is the shortcut for Monitor.Enter with the try and finally.
This means that the following code
static object _lock = new object();
public static void AddOneMillion()
{
for (int i = 1; i <= 1000000; i++)
{
lock (_lock)
{
Total++;
}
}
}
can be rewritten as shown below:
static object _lock = new object();
public static void AddOneMillion()
{
for (int i = 1; i <= 1000000; i++)
{
// Acquires the exclusive lock
Monitor.Enter(_lock);
try
{
Total++;
}
finally
{
// Releases the exclusive lock
Monitor.Exit(_lock);
}
}
}
From C# 4, it is implemented slightly differently as shown below
static object _lock = new object();
public static void AddOneMillion()
{
for (int i = 1; i <= 1000000; i++)
{
bool lockTaken = false;
// Acquires the exclusive lock
Monitor.Enter(_lock, ref lockTaken);
try
{
Total++;
}
finally
{
// Releases the exclusive lock
if (lockTaken)
Monitor.Exit(_lock);
}
}
}
So, in short, the lock is a shortcut and it’s the option for basic usage. If we need
more control to implement advanced multithreading solutions using TryEnter(), Wait(),
Pulse(), & PulseAll() methods, then the Monitor class is our option.
Explain why and how a deadlock can occur in multithreading with an
example?
This is one of the most frequently asked Deadlock Interview Questions in C#. Let’s say
we have 2 threads Thread 1 and Thread 2 and 2 resources Resource 1 and Resource
2. Thread 1 has already acquired a lock on Resource 1 and wants to acquire a lock on
Resource 2. At the same time, Thread 2 has already acquired a lock on Resource 2 and
wants to acquire a lock on Resource 1. Two threads never give up their locks, hence a
deadlock.
How to resolve a deadlock in a multithreaded program?
There are several techniques to avoid and resolve deadlocks. For example
1. Acquiring locks in a specific defined order
2. Mutex class
3. Monitor.TryEnter() method
What is AutoResetEvent and how it is different from
ManualResetEvent?
This is one of the most frequently asked Deadlock Interview Questions in
C#. The AutoResetEvent is used when we have to unlock only one single thread from
several waiting blocked threads. Below are the differences from ManualResetEvent.
1. ManualResetEvent is used for unblocking many threads simultaneously.
But AutoResetEvent is used for unblocking only one single thread.
2. You have to call Reset() method manually after calling Set() method to
reset the ManualResetEvent. But AutoResetEvent Set() method
automatically calls the Reset() method.
What is the Semaphore?
This is one of the most frequently asked Deadlock Interview Questions in C#. Semaphores
are used when we have to restrict how many threads can enter a critical region.
Semaphore is simply an int32 variable maintained by the kernel. We have initialized the
Semaphore variable we specify the count of how many threads can enter into the critical
region at a time. A thread waiting on a semaphore block when the semaphore is 0 and
unblocks when the semaphore is greater than 0.
class Program
{
static Semaphore semaphore = new Semaphore(5, 5);
static void Main(string[] args)
{
Task.Factory.StartNew(() =>
{
for (int i = 1; i <= 15; ++i)
{
PrintSomething(i);
if (i % 5 == 0)
{
Thread.Sleep(2000);
}
}
});
Console.ReadLine();
}
public static void PrintSomething(int number)
{
semaphore.WaitOne();
Console.WriteLine(number);
semaphore.Release();
}
}
When we create instantiate a semaphore object, we have to provide two parameters in
the constructor. The first one is the InitialCount and the second one is
MaximumCount. MaximumCount denotes the maximum number of threads that can enter
concurrently. InitialCount denotes the initial number of threads which can enter the
Semaphore directly.
Threads enter the semaphore by calling the WaitOne method and release the semaphore
by calling the Release method. You can release multiple threads bypassing the count in
the Release method. By default Release method takes one and only releases one thread.
What is Mutex and how it is different from other Synchronization
mechanisms?
This is one of the most frequently asked Deadlock Interview Questions in C#. Mutex works
similarly to AutoResetEvent and releases only one waiting thread at a time. In the
AutoResetEvent any thread can call the Set() method and unblock a waiting thread. But
the Mutex object remembers the thread which got the Mutex object and only that thread
can release the Mutex.
Mutex object auto record the thread id which got the Mutex object and when a user calls
the ReleaseMutex() method for releasing a Mutex object, it internally checks whether the
releasing thread is the same as the thread which got the Mutex object if yes, then only it
releases the Mutex object else it throws an exception.
Mutex famous example: The mutex is like a key to a toilet. One person can have the key
– occupy the toilet – at the time. When finished, the person gives (frees) the key to the
next person in the queue.
What is the Race condition?
A race condition happens when two or more threads want to update shared data at the
same time.
What is the volatile keyword?
Volatile is used for serializing the access of variables without using the synchronization
primitives. You can use volatile with below types:
1. References type
2. Pointer types
3. Values types
4. IntPtr
How can you share data between multiple threads?
There are two ways to share data between multiple threads:
1. Concurrent collection classes
2. Using Synchronization Primitives
What are Concurrent Collection Classes?
.NET Framework class library comes with Concurrent collection classes so that multiple
threads can share collection data between them without using synchronization primitives.
There are four types of Concurrent classes.
1. ConcurrentQueue
2. ConcurrentStack
3. ConcurrentDictionary
4. ConcurrentBag
What is synchronization and why it is important?
This is one of the most frequently asked Deadlock Interview Questions in C#. We use
multiple threads to improve the performance of our application. When multiple threads
shares data between there is a chance of data corruption. When one thread is writing to
the variable and another thread is reading the same variable at the same time there is a
chance of reading corrupt data.
To stop the dirty reads we use synchronization primitives.
Can you count some names of Synchronization primitives?
1. Monitor
2. Mutex
3. Spinlock
4. ReaderWriterLock
5. Semaphore
6. AutoResetEvent
7. ManualResetEvent
8. Interlocked
9. CountDownEvent
10. Barrier
What are the four necessary conditions for Deadlock?
1. Mutual Exclusion: Resources involved must be unshareable between
multiple threads.
2. Hold and Wait: Threads hold the resources they have allocated and
wait for the resources they want.
3. No pre-emption: If the thread locks the resource, other threads cannot
take the resource until the thread releases it.
4. Circular Wait: A circular chain must exist in which each thread waits
for other threads to release resources.
What is LiveLock?
This is one of the most frequently asked Deadlock Interview Questions in C#. A livelock is
very similar to a deadlock except for involved threads states are continually changing their
state but still, they cannot complete their work.
A real-world example of livelock occurs when two people meet in a narrow corridor, and
each tries to be polite by moving aside to let the other pass, but they end up swaying from
side to side without making any progress because they both repeatedly move the same
way at the same time.
Exception Handling Interview Questions in C# with
Answers
In this article, I am going to discuss the most frequently asked Exception Handling
Interview Questions in C# with Answers. Please read our previous article where we
discussed the most frequently asked Multithreading and Deadlock Interview
Questions in C# with Answers. As part of this article, we are going to discuss the following
Exception Handling Interview Questions in C# with Answers.
Advertisements
What is an Exception?
A runtime error is known as an exception. An exception cannot be identified and rectified
by the programmer. The exception will cause abnormal termination of the program
execution.
So these errors (exceptions) are very dangerous because whenever an exception occurs
in the programs the program gets terminated abnormally on the same line where the error
gets occurred without executing the next line of code.
Who is responsible for abnormal termination of the program whenever
runtime errors occur?
The Objects of exception classes are responsible for abnormal termination of the program
whenever runtime errors occur. These exception classes are predefined under BCL where
a separate class is provided for each and every different type of exception like
1. IndexOutOfRangeException
2. FormatException
3. NullReferenceException
4. DivideByZeroException
5. FileNotFoundException
6. SQLException,
7. OverFlowException, etc.
Each exception class provides specific exception error message.
All exception classes are responsible for abnormal termination of the program as well as
after abnormal termination of the program they will be displaying an error message which
specifies the reason for abnormal termination i.e. they provide an error message specific
to that error.
Whenever a runtime error occurs in a program, first the exception manager under CLR
identifies the type of error that occur in the program, creates an object of the exception
class related with that error and throws that object which will immediately terminate the
program abnormally on the line where error got occur and display the error message
related with that class.
What happens if an exception is raised in the program?
Program execution is terminated abnormally. It means statements placed after exception
causing statement are not executed but the statements placed before that exception
causing statement are executed by CLR.
What CLR does when a logical mistake occurred in the program?
This is one of the frequently asked Exception Handling Interview Questions in C#.
It creates an exception class object that is associated with that logical mistake and
terminates the current method execution by throwing that exception object by using the
“throw” keyword.
So we can say an exception is an event that occurs during the execution of a program that
disrupts the normal flow of instruction execution.
Below program shows program execution without exception:
namespace ExceptionHandlingDemo
class Program
int a = 20;
int b = 10;
int c;
c = a / b;
Console.ReadKey();
}
Below program shows program execution with exception:
namespace ExceptionHandlingDemo
class Program
{
static void Main(string[] args)
int a = 20;
int b = 0;
int c;
c = a / b;
Console.ReadKey();
}
Output:
a value = 20
b value = 0
DivideByZeroException was unhandled Attempt to divide by zero.
Explanation: CLR terminates this program execution by throwing
DivideByZeroException because the logical mistake we committed is dividing integer
number by integer zero. As we know it is not possible to divide an integer number by zero.
From the above program, we can define the exception technically as “An exception is an
event because when an exception is raised CLR internally executes some logic to prepare
that exception related messages”.
The exception is a signal because by looking into exception message developer will take
necessary actions against that exception. An exception is an object because for throwing
exception CLR or we should create an appropriate class object.
Is the above exception message is user understandable?
Definitely, no, the user cannot understand the above exception message because they
are .NET based exception messages. So the user cannot take further decision alone to
resolve the above problem. The developer should guide to solve the above problem.
What is the solution for the above problem?
It is developer responsibility to convert .NET exception messages into user
understandable message format. To solve this problem developer should write exception
handling code in a .NET program. Using exception handling code, the developer can catch
the exception and can print and pass user understandable messages.
What is Exception Handling in C#?
This is one of the frequently asked Exception Handling Interview Questions in C#.
The process of catching the exception for converting CLR given exception message to
end-user understandable message or for stopping the abnormal termination of the
program whenever runtime errors are occurring is called exception handling. Once we
handle an exception under a program we will be getting following advantages
1. We can stop the abnormal termination
2. We can perform any corrective action that may resolve the
problem occurring due to abnormal termination.
3. Displaying a user-friendly error message, so that the client can resolve the
problem provided if it is under his control.
Why we need exception handling in C#?
In projects, an exception is handled
1. To stop the abnormal termination of the program
2. To provide user understandable messages when an exception is raised.
So that users can make the decision without the help of developers.
Basically, by implementing Exception handling we are providing life to a program to talk
to the user on behalf of a developer.
What is the Exception Handling Procedure?
Exception handling is a 4 steps procedure
1. Preparing the exception objects appropriate to the current logical mistake.
2. Throwing that exception to the appropriate exception handler.
3. Catching that exception
4. Taking necessary actions against that exception
How can we handle the exception in .NET?
There are three methods to handle the exception in .NET
1. Logical implementation
2. Try catch implementation
3. On error go to implementation
Explain the difference between Error and Exception in C#?
This is one of the frequently asked Exception Handling Interview Questions in C#.
Exceptions are those which can be handled at the runtime whereas errors cannot be
handled.
An exception is an object of a type deriving from the System.Exception class. The
exception is thrown by the CLR (Common Language Runtime) when errors occur that are
nonfatal and recoverable by user programs. It is meant to give you an opportunity to do
something with a throw statement to transfer control to a catch clause in a try block.
The error is something that most of the time we cannot handle it. Errors are the unchecked
exception and the developer is not required to do anything with these. Errors normally
tend to signal the end of our program, it typically cannot be recovered from and should
cause us to exit from the current program. It should not be caught or handled.
All the Errors are Exceptions but the reverse is not true. In general, Errors are which
nobody can control or guess when it happened on the other hand Exception can be
guessed and can be handled.
What is the difference between System exceptions and Application
exceptions?
System exceptions are derived directly from a base class System.SystemException. A
System-level Exception is normally thrown when a nonrecoverable error has occurred.
Application exceptions can be user-defined exceptions thrown by the applications. If you
are designing an application that needs to create its own exceptions class, you are advised
to derive custom exceptions from the System.ApplicationException class. It is typically
thrown when a recoverable error has occurred.
What is the logical implementation?
In this method, we handle the exception by using logical statements. In real-time
programming, the first and foremost important always given to logical implementation. If it
is not possible to handle an exception using logical implementation then we use try-catch
implementation.
Program to handle an exception using logical implementation.
namespace ExceptionHandlingDemo
class Program
b = int.Parse(Console.ReadLine());
int a, b, c;
a = int.Parse(Console.ReadLine());
if (b == 0)
else
c = a / b;
Console.ReadKey();
}
}
In the above example when the user entered the second number as zero exception will
be raised and that is handled using logical implementation.
But while we are entering two numbers instead of the number if we entered any character
then it will give you one exception that FormatException which is not handled in this
program. So to handle such type of exception we need to go for Try catch implementation.
Explain about try-catch implementation.
To implement the try-catch implementation .NET provides three keywords
1. Try
2. Catch
3. finally
try: try keyword establishes a block in which we need to write the exception causing and
its related statements. That means exception causing statements must be placed in the
try block so that we can handle and catch that exception for stopping abnormal termination
and to display end-user understandable messages.
Catch: The catch block is used to catch the exception that is thrown from its
corresponding try block. It has logic to take necessary actions on that caught exception.
Catch block syntax looks like a constructor. It does not take accessibility modifier, normal
modifier, return type. It takes a single parameter of type Exception.
Inside catch block, we can write any statement which is legal in .NET including raising an
exception. If the catch block is used without an exception class then it is known as a
generic catch block. If the catch block is used with exception class then it is known as a
specific catch block.
Finally: Finally establishes a block that definitely executes statements placed in
it. Statements that are placed in finally block are always executed irrespective of the way
the control is coming out from the try block either by completing normally or throwing an
exception by catching or not catching.
SYNTAX TO USE TRY CATCH:
Once we enclose the code under try and catch blocks the execution
takes place as following
If all the statements under try are executed successfully from the last statement of trying
the control directly jumps to the first statement that is present after the catch block (after
all catch blocks) without executing catch block (it means there is no runtime error in the
code at all ).
If any of the statements in the try causes an error from that statement without executing
any other statements in try control directly jumps to the catch blocks searching for a catch
block to handle that exception.
If a proper catch block is available that can handle the exception and abnormal termination
stops there, executes the code under the catch block and from there again it jumps to the
first statement after all the catch blocks. If a matching catch is not available abnormal
termination occurs again.
Explain the Properties of the Exception class.
The exception class has 3 properties are as follows
1. Message: This property will store about the reason why the exception has
occurred.
2. Source: This store name of the application from where the exception has
been raised.
3. Helplink: This is used to provide a link to any file /URL to give helpful
information to the user when an exception is raised.
Example to show the use of Exception (superclass of all exception classes) class
as an argument in catch blocks.
In the above example, the superclass exception is used to handle the exception. But if we
use super of any exception class when there is any relevant class is available, it will kill
the execution performance of the program. So any time doesn’t use the superclass of an
exception class to handle an exception when there is a relevant exception class is
available.
Can we catch all exceptions using a single catch block?
Yes, we can catch all exceptions with a single catch block with parameter “Exception”. We
should use this catch block only for stopping abnormal termination irrespective of the
exceptions thrown from its corresponding try block.
It is always recommended to write catch blocks with exception parameters even though
we are writing multiple catch blocks. It acts as a backup catch block.
When should we write multiple catch blocks for a single try block?
We should write multiple catch blocks for a single try block because of the following
reasons
1. To print message specific to an exception or
2. To execute some logic specific to an exception
Explain about the finally block.
Finally establishes a block that definitely executes statements placed in it. The Statements
which are placed in finally block are always executed irrespective of the way the control is
coming out from the try block either by completing normally or throwing the exception by
catching or not catching.
Why we need finally block in the real-time project?
As per coding standard in finally block we should write resource releasing logic or clean
up the code. Resource releasing logic means un-referencing objects those are created in
the try block. For example, in real time projects, we create ADO.NET objects in the try
block and at the end of the try block, we must close these objects.
Since the statements written in try and catch block are not guaranteed to be executed we
must place them in finally block. For example, if we want to close ADO objects such as
Connection object, Command object, etc. we must call the close() method in both try as
well as in catch block to guarantee its execution.
Instead of placing the same close() method call statements in multiple places if we write
it in finally block it is always executed irrespective of the exception raised or not raised.
How many ways we can use try catch and finally?
In can use in three different combinations
1. Try and catch: In this case, execution will be handled and stopping the
abnormal termination.
2. The Try, catch and finally: In this case also exception will be handled
stopping the abnormal termination along with the statements that are placed
within the finally block gets executed at any cost.
3. Try and finally: In this case abnormal will not stop when a runtime error
occurs because exceptions are not handled but even if the abnormal
termination occurs also finally blocks get executed.
What happens if the finally block throws an exception?
The exception propagates up and should be handled at a higher level. If the exception is
not handled at a higher level, the application crashes. The “finally” block execution stops
at the point where the exception is thrown.
In the example below, notice that the “finally” block in the “Hello()” method throws an
exception. Hello() method is being called in the Main() method and we don’t have any
exception handling mechanism in place in the Main() method. So, the application crashes
with the exception.
public class Program
Hello();
}
public static void Hello()
try
// Some code
catch
// Some code
finally
}
On the other hand, if you include exception handling mechanism(try/catch) in
the Main() method, then you will have the opportunity to handle the exception.
public static void Main()
try
Hello();
}
catch (Exception ex)
Console.WriteLine(ex.Message);
}
Irrespective of whether there is an exception or not “finally” block is
guaranteed to execute.
1. If the “finally” block is being executed after an exception has occurred in
the try block,
2. and if that exception is not handled
3. and if the finally block throws an exception
Then the original exception that occurred in the try block is lost.
Here is an example:
public class Program
try
Hello();
Console.WriteLine(ex.Message);
{
try
finally
}
What is the difference between the “throw” and “throw ex” in .NET?
throw re-throws the exception that was caught, and preserves the stack trace. throw ex-
throws the same exception, but resets the stack trace to that method. Unless you want to
reset the stack trace (i.e. to shield public callers from the internal workings of your library),
the throw is generally the better choice, since you can see where the exception originated.
Throw Syntax:
try
throw;
//Throw ex Syntax:
try
{
throw ex;
}
What is Inner Exception?
The InnerException property returns the Exception instance (original exception) that
caused the current exception.
To look at the inner exception, we have to make this program cause an exception to fail.
To do that you have 3 options
1. Enter a Character instead of a number (Causes Format Exception)
2. Or Enter a very big number that an integer cannot hold (Causes Over
Flow Exception)
3. Or Enter Zero for Second Number (Causes Divide By Zero Exception)
class ExceptionHandling
try
try
int FN = Convert.ToInt32(Console.ReadLine());
int SN = Convert.ToInt32(Console.ReadLine());
if (File.Exists(filePath))
sw.Close();
else
if (ex.InnerException != null)
1. What is RDBMS?
2. Explain DML, DDL, DCL, and TCL statements with examples?
3. What is the difference between Drop, Delete and Truncate statements in
SQL Server?
4. What is the Cascading referential integrity constraint?
5. Explain the difference between where clause and having clause in SQL
Server
6. What are the differences between primary key and unique key in SQL
Server?
7. How can we copy the data from one table to another?
8. How to create a new table from an existing table or in how many ways
we can create a new table from an existing table?
9. What is normalization?
10. What are the different normalization forms?
11. What is the Cursor?
12. What is the use of DBCC commands?
13. What is a Linked Server?
14. What is Collation?
15. What are the different types of Collation Sensitivity?
16. How to implement one-to-one, one-to-many and many-to-many
relationships while designing tables?
17. What is a NOLOCK?
18. What is the use of the UPDATE_STATISTICS command?
19. What is sub-query? Explain the properties of sub-query.
20. What is the SQL Profiler?
21. What are the authentication modes in SQL Server? How can it be
changed?
22. What is an SQL server agent?
23. What is log shipping?
24. What are sp_configure commands and set commands?
25. What are the different types of replication?
26. What does it mean to have quoted_identifier on?
27. What are the implications of having it off?
28. What is the STUFF function and how does it differ from the
REPLACE function?
29. How to rebuild the Master Database?
30. What are the basic functions for master, msdb, model, tempdb
databases?
31. What is De-normalization?
32. What is Scheduled Jobs or What is a Scheduled Tasks?
33. What is BCP? When does it use?
34. How do you load large data to the SQL server database?
35. Can we rewrite subqueries into simple select statements or with
joins?
36. Can SQL Servers link to other servers like Oracle?
37. How to copy the tables, schema, and views from one SQL server to
another?
38. What is data warehousing?
39. What is OLTP (Online Transaction Processing)?
40. What is Data Integrity?
41. What are the different levels of data integrity in SQL Server?
42. What is Entity integrity?
43. What is Referential integrity?
44. What is Domain Integrity?
45. What is user-defined integrity?
46. What is a Constraint in SQL Server?
47. Why do we need Constraints in SQL Server?
48. What are the different types of Constraints available in SQL Server?
49. What is Default Constraint in SQL Server?
50. What is NOT NULL Constraint in SQL Server?
51. What is a Unique Constraint in SQL Server?
52. What is a composite constraint in SQL Server?
53. What is CHECK Constraint in SQL Server?
54. What is the Primary Key Constraint in SQL Server?
55. What is a Composite Primary Key in SQL Server?
56. What is Foreign Key Constraint in SQL Server?
57. How can we provide the default value for a column?
58. What is SELF REFERENTIAL INTEGRITY
59. What is the difference between a primary key and a unique key?
60. What is the difference between primary key and foreign key?
What is RDBMS?
Relational Database Management Systems (RDBMS) are database management
systems that maintain data records and indices in tables. Relationships may be created
and maintained across and among the data and tables. In a relational database,
relationships between data items are expressed by means of tables. Interdependencies
among these tables are expressed by data values rather than by pointers.
This allows for a high degree of data independence. An RDBMS has the capability to
recombine the data items from different files, providing powerful tools for data usage.
Explain DML, DDL, DCL, and TCL statements with examples?
This is one of the most frequently asked SQL Server Interview Questions. Let us
understand the above terms in detail.
DML:
DML stands for Data Manipulation Language. DML is used to retrieve, insert, update, and
delete data in a database that means DML statements affect records in a table. These are
basic operations we perform on data such as selecting a few records from a table,
inserting new records, deleting unnecessary records, and updating/modifying existing
records. DML statements include the following:
SELECT – select records from a table
INSERT – insert new records
UPDATE – update/Modify existing records
DELETE – delete existing records
DDL:
DDL stands for Data Definition Language. DDL statements are used to alter/modify a
database or table structure and schema. These statements handle the design and storage
of database objects.
CREATE – create a new Table, database, schema
ALTER – alter the existing table, column description
DROP – delete existing objects from a database
DCL:
DCL stands for data control language. Generally, we will use these commands to secure
database objects by creating roles, permissions using GRANT, REVOKE operations. In
SQL Server, the following operations will come under DCL operations
GRANT – allows users to read/write on certain database objects
REVOKE – keeps users from the read/write permission on database objects
TCL:
TCL stands for Transactional Control Language. TCL is used to manage transactions
within a database. Examples: COMMIT, ROLLBACK, Begin Transaction statements
BEGIN Transaction – opens a transaction
COMMIT Transaction – commits a transaction
ROLLBACK Transaction – ROLLBACK a transaction in case of any error
What is the difference between Drop, Delete and Truncate statements
in SQL Server?
This is one of the frequently asked SQL Server Interview Questions. The Drop, Delete,
and Truncate – All operations can be rolled back.
Delete command removes the rows from a table based on the condition that we provide
with a WHERE clause. Truncate will actually remove all the rows from a table and there
will be no data in the table after we run the truncate command.
All the statements (Delete, Truncate, and Drop) are logged operations but the amount of
information that is logged varies. Delete statement logs an entry in the transaction log for
each deleted row, whereas Truncate Table logs only the Page deallocations. Hence,
truncate is a little faster than Delete.
DELETE:
1. The DELETE command is used to remove some or all rows from a table.
2. A WHERE clause can be used with a DELETE command to remove some
specific rows from a table.
3. If the WHERE condition is not specified, then all rows are removed.
4. The DELETE operation will cause all DELETE triggers on the table to fire.
5. It does not reset the identity of the column value.
6. It removes rows on a row-by-row basis and hence for each deleted row it
records an entry in the transaction logs, thus this is slower than truncate.
7. This is a DML command so it is just used to manipulate or modify the table
data and it does not change any property of a table.
TRUNCATE:
1. TRUNCATE removes all rows from a table, but the table structure and its
columns, constraints, indexes, and so on remain.
2. It does not require a WHERE clause, so we cannot filter rows while
Truncating.
3. IDENTITY columns are re-seeded on this operation if no seed was defined
then the default value 1 is used.
4. No Triggers are fired on this operation because it does not operate on
individual rows.
5. TRUNCATE removes the data by deallocating the data pages used to
store the table’s data instead of rows and records, and only the page
deallocations are recorded in the transaction log thus it is faster than delete.
6. We cannot use TRUNCATE TABLE on a table referenced by a FOREIGN
KEY constraint.
7. TRUNCATE is DDL Command
DROP:
1. The DROP command removes a table from the database.
2. All the related Data, Indexes, Triggers, Constraints, and Permission
specifications for the Table are dropped by this operation.
3. Some objects like Views, Stored Procedures that reference the dropped
table are not dropped and must be explicitly dropped.
4. Cannot drop a table that is referenced by any Foreign Key constraint.
5. No Triggers are fired on this operation because it does not operate on
individual rows.
Note: If TRUNCATE is written in Query Editor surrounded by TRANSACTION and if the
session is closed, it cannot be rolled back but DELETE can be rolled back.
What is the Cascading referential integrity constraint?
This is one of the most frequently asked SQL Server Interview Questions. Cascading
referential integrity constraints are foreign key constraints that tell SQL Server to perform
certain actions when a user attempts to delete or update a primary key to which an
existing foreign keys point.
SET NULL: If a delete or update statement affects rows in a foreign key table, those
values will be set to NULL when the primary key record is deleted or updated. The foreign
key columns affected must allow NULL values.
CASCADE: If a delete statement affects one or more rows in a foreign key table, those
rows will be deleted when the primary key record is deleted. If an update statement affects
rows in the foreign key table, those rows will be updated with the value from the primary
key record after it has been updated.
SET DEFAULT: If a delete or update statement affects rows in a foreign key table, then
all rows containing those foreign keys are set to the default value. All foreign key columns
in the related table must have default constraints defined on them.
NO ACTION: This is the default action. This specifies that if an update or deletes
statement affects rows in foreign key tables, then the action will be denied and rolled back.
An error message will be raised.
What is the difference between where clause and having clause in
SQL Server?
This is one of the most frequently asked SQL Server Interview Questions and in almost
all interviews this question being asked.
1. WHERE clause cannot be used with aggregate functions whereas the
HAVING clause can be used with aggregate functions. This means the
WHERE clause is used for filtering individual rows on a table whereas the
HAVING clause is used to filter groups.
2. WHERE comes before GROUP BY. This means the WHERE clause filters
rows before aggregate calculations are performed. HAVING comes after
GROUP BY. This means the HAVING clause filters rows after aggregate
calculations are performed. So, from a performance standpoint, HAVING is
slower than WHERE and should be avoided when possible.
3. WHERE and HAVING clause can be used together in a SELECT query. In
this case WHERE clause is applied first to filter individual rows. The rows
are then grouped and aggregate calculations are performed, and then the
HAVING clause filters the groups.
4. WHERE clause can be used with – Select, Insert, and Update statements
whereas the HAVING clause can only be used with the Select statement.
What are the differences between primary key and unique key in SQL
Server?
This is of the most asked SQL Server Interview Questions in Interviews. Let discuss this
question in detail.
1. A table can have only one primary key. On the other hand, a table can
have more than one unique key.
2. The primary key column does not accept any null values whereas a
unique key column accepts one null value.
3. Both Primary key and unique key enforce the uniqueness of the column
on which they are defined. But By default, the primary key creates a unique
clustered index on the column whereas a unique key creates a unique non
clustered index.
How can we copy the data from one table to another?
This is one of the most frequently asked SQL Server Interview Questions and the
interviewer basically asked to write the query. When we copy the data from one table to
another table then the two tables should contain the same structure.
When we copy the data from one table to another table we use insert and select
query. Tables always independent objects that mean a table does not depend on other
tables
How to create a new table from an existing table or in how many ways
we can create a new table from an existing table?
If required we can create a new table from an existing table as below.
Syntax1: (with all column from an existing table)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
Example: SELECT * INTO NEWEMPLOYEE FROM EMPLOYEE
When we execute the above query it will create a new table with all records from an
existing table.
Syntax2: (with specific columns from an existing table)
SELECT <REQUIREDCOLUMN> INTO <NEW TABLE NAME> FROM <OLD TABLE N
AME>
Example: SELECT EID, SALARY INTO SPECEMP FROM EMPLOYEE
When we execute the above query it will create a new table with the specific column
data from an existing table.
Syntax3: (creating a new table without data)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME> WHERE 1 = 0
Example: SELECT * INTO DUMMYEMP FROM EMPLOYEE WHERE 1 = 0
OR
SELECT <REQUIRED COLUMNS> INTO <NEW TABLE NAME> FROM
<OLD TABLE NAME>
SELECT EID, SALARY INTO TAB1 FROM EMPLOYEE WHERE 1 = 0
When we execute the above query it will create a new table without records from an
existing table.
What is normalization?
Database normalization is a data design and organization process applied to data
structures based on rules that help build relational databases. In relational database
design the process of organizing data to minimize redundancy. Normalization usually
involves dividing a database into two or more tables and defining relationships between
the tables. The objective is to isolate data so that additions, deletions, and modifications
of a field can be made in just one table and then propagated through the rest of the
database via the defined relationships.
What are the different normalization forms?
This is one of the frequently asked SQL Server Interview Questions.
1NF: Eliminate Repeating Groups: Make a separate table for each set of related
attributes, and give each table a primary key. Each field contains at most one value from
its attribute domain.
2NF: Eliminate Redundant Data: If an attribute depends on only part of a multi-valued
key, remove it to a separate table.
3NF: Eliminate Columns Not Dependent On Key: If attributes do not contribute to a
description of the key, remove them to a separate table. All attributes must be directly
dependent on the primary key
BCNF: Boyce-Codd Normal Form: If there are non-trivial dependencies between
candidate key attributes, separate them out into distinct tables.
4NF: Isolate Independent Multiple Relationships: No table may contain two or more
1:n or n:m relationships that are not directly related.
5NF: Isolate Semantically Related Multiple Relationships: There may be practical
constrains on information that justifies separating logically related many-to-many
relationships.
ONF: Optimal Normal Form: A model limited to only simple (elemental) facts, as
expressed in Object Role Model notation.
DKNF: Domain-Key Normal Form: A model free from all modification anomalies.
Remember, these normalization guidelines are cumulative. For a database to be in 3NF,
it must first fulfill all the criteria of a 2NF and 1NF database. Please click here to
learn Database Normalization in detail step by step with some real-time examples.
What is the Cursor?
A cursor is a database object used by applications to manipulate data in a set on a row-
by-row basis, instead of the typical SQL commands that operate on all the rows in the set
at one time.
In order to work with a cursor we need to perform some steps in the following order:
1. Declare cursor
2. Open cursor
3. Fetch row from the cursor Process fetched row Close cursor
4. Deallocate cursor
What is the use of DBCC commands?
DBCC stands for database consistency checker. We use these commands to check the
consistency of the databases, i.e., maintenance, validation task, and status checks. For
example,
1. DBCC CHECKDB – Ensures that tables in the DB and the indexes are
correctly linked.
2. DBCC CHECKALLOC – To check that all pages in a DB are correctly
allocated.
3. DBCC CHECKFILEGROUP – Checks all tables file group for any damage.
What is a Linked Server?
Linked Servers is a concept in SQL Server by which we can add other SQL Server to a
Group and query both the SQL Server DBS using T-SQL Statements. With a linked server,
you can create very clean, easy to follow, SQL statements that allow remote data to be
retrieved, joined, and combined with local data. Stored
Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used to add a new
Linked Server.
What is Collation?
Collation refers to a set of rules that determine how data is sorted and compared.
Character data is sorted using rules that define the correct character sequence, with
options for specifying case-sensitivity, accent marks, kana character types, and character
width.
What are the different types of Collation Sensitivity?
1. Case sensitivity: A and a, B and b, etc.
2. Accent sensitivity: a and á, o and ó, etc.
3. Kana Sensitivity: When Japanese kana characters Hiragana and Katakana
are treated differently, it is called Kana sensitive.
4. Width sensitivity: When a single-byte character (half-width) and the same
character when represented as a double-byte character (full-width) are treated
differently than it is width sensitive.
How to implement one-to-one, one-to-many and many-to-many
relationships while designing tables?
1. The one-to-one relationship can be implemented as a single table and
rarely as two tables with primary and foreign key relationships.
2. One-to-Many relationships are implemented by splitting the data into two
tables with primary key and foreign key relationships.
3. Many-to-Many relationships are implemented using a junction table with
the keys from both the tables forming the composite primary key of the
junction table.
What is a NOLOCK?
This is one of the most frequently asked SQL Interview Questions. Using the NOLOCK
query optimizer hint is generally considered good practice in order to improve concurrency
on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks
are taken when data is read. The result is a Dirty Read, which means that another process
could be updating the data at the exact time you are reading it. There are no guarantees
that your query will retrieve the most recent data.
The advantage of performance is that your reading of data will not block updates from
taking place, and updates will not block your reading of data. SELECT statements take
Shared (Read) locks. This means that multiple SELECT statements are allowed
simultaneous access, but other processes are blocked from modifying the data. The
updates will queue until all the reads have completed, and reads requested after the
update will wait for the updates to complete. The result of your system is the
delay(blocking).
When is the use of the UPDATE_STATISTICS command?
This is one of the most frequently asked SQL Interview Questions. This command is
basically used when a large processing of data has occurred. If a large number of
deletions any modification or Bulk Copy into the tables has occurred, it has to update the
indexes to take these changes into account. UPDATE_STATISTICS updates the indexes
on these tables accordingly.
What is sub-query? Explain the properties of sub-query.
This is one of the frequently asked SQL Server Interview Questions. Sub-queries are often
referred to as sub-selects, as they allow a SELECT statement to be executed arbitrarily
within the body of another SQL statement. A sub-query is executed by enclosing it in a set
of parentheses. Sub-queries are generally used to return a single row as an atomic value,
though they may be used to compare values against multiple rows with the IN keyword.
A subquery is a SELECT statement that is nested within another T-SQL statement. A
subquery SELECT statement if executed independently of the T-SQL statement, in which
it is nested, will return a result set. Meaning a subquery SELECT statement can stand
alone and is not dependent on the statement in which it is nested. A subquery SELECT
statement can return any number of values and can be found in, the column list of a
SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a T-
SQL statement. A Subquery can also be used as a parameter to a function call. Basically,
a subquery can be used anywhere an expression can be used.
Properties of Sub-Query
1. A subquery must be enclosed in the parenthesis.
2. The subquery must be put in the right hand of the comparison operator, and
3. The subquery cannot contain an ORDER-BY clause.
4. A query can contain more than one sub-queries.
What are the types of sub-queries?
1. Single-row subquery, where the subquery returns only one row.
2. Multiple-row subquery, where the subquery returns multiple rows
3. Multiple column subquery, where the subquery returns multiple columns.
What is the SQL Profiler?
This is one of the most frequently asked SQL Server Interview Questions. SQL Profiler is
a graphical tool that allows system administrators to monitor events in an instance of
Microsoft SQL Server. You can capture and save data about each event to a file or SQL
Server table to analyze later. For example, you can monitor a production environment to
see which stored procedures are hampering performance by executing too slowly.
Use SQL Profiler to monitor only the events in which you are interested. If traces are
becoming too large, you can filter them based on the information you want, so that only a
subset of the event data is collected. Monitoring too many events adds overhead to the
server and the monitoring process and can cause the trace file or trace table to grow very
large, especially when the monitoring process takes place over a long period of time.
Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP
properties –> Port number. both on the client and the server.
What are the authentication modes in SQL Server? How can it be
changed?
Windows mode and mixed mode (SQL & Windows). To change authentication mode in
SQL Server click Start, Programs, Microsoft SQL Server, and click SQL Enterprise
Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group.
Select the server then from the Tools menu select SQL Server Configuration Properties,
and choose the Security page.
Advertisements
Where are SQL server users names and passwords are stored in
SQL server?
They get stored in master DB in the sysxlogins table.
Which command using Query Analyzer will give you the version of SQL
server and operating system?
SELECT SERVERPROPERTY(‘productversion’), SERVERPROPERTY (‘productlevel’),
SERVERPROPERTY (‘edition’)
What is the SQL server agent?
This is one of the frequently asked SQL Server Interview Questions. SQL Server agent
plays an important role in the day-to-day tasks of a database administrator (DBA). It is
often overlooked as one of the main tools for SQL Server management. Its purpose is to
ease the implementation of tasks for the DBA, with its full-function scheduling engine,
which allows you to schedule your own jobs and scripts.
What is log shipping?
Log shipping is the process of automating the backup of database and transaction log files
on a production SQL server and then restoring them onto a standby server. Enterprise
Editions only supports log shipping. In log shipping, the transnational log file from one
server is automatically updated into the backup database on the other server. If one server
fails, the other server will have the same DB that can be used as the Disaster Recovery
plan. The key feature of log shipping is that it will automatically backup transaction logs
throughout the day and automatically restore them on the standby server at a defined
interval.
What command do we use to rename a DB?
sp_renamedb ‘oldname’, ‘newname’
If someone is using DB it will not accept sp_renmaedb. In that case, first, bring DB to the
single user using sp_dboptions. Use sp_renamedb to rename the database. Use
sp_dboptions to bring the database to multi-user mode.
What are sp_configure commands and set commands?
Use sp_configure to display or change server-level settings. To change database-level
settings, use ALTER DATABASE. To change settings that affect only the current user
session, use the SET statement.
What are the different types of replication? Explain.
The SQL Server 2000-supported replication types are as follows:
1. Transactional
2. Snapshot
3. Merge
Snapshot replication distributes data exactly as it appears at a specific moment in time
and does not monitor for updates to the data. Snapshot replication is best used as a
method for replicating data that changes infrequently or where the most up-to-date values
(low latency) are not a requirement. When synchronization occurs, the entire snapshot is
generated and sent to Subscribers.
In transactional replication, an initial snapshot of data is applied at Subscribers, and then
when data modifications are made at the Publisher, the individual transactions are
captured and propagated to Subscribers.
Merge replication is the process of distributing data from Publisher to Subscribers,
allowing the Publisher and Subscribers to make updates while connected or disconnected,
and then merging the updates between sites when they are connected.
What are the OS services that the SQL Server installation adds?
MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-
ordinator)
What are three SQL keywords used to change or set someone’s
permissions?
GRANT, DENY, and REVOKE.
What does it mean to have quoted_identifier on? What are the
implications of having it off?
When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation
marks, and literals must be delimited by single quotation marks. When SET
QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact-
SQL rules for identifiers.
What is the STUFF function and how does it differ from the REPLACE
function?
STUFF function to overwrite existing characters. Using this syntax,
STUFF(string_expression, start, length, replacement_characters), string_expression is
the string that will have characters substituted, the start is the starting position, the length
is the number of characters in the string that are substituted, and replacement_characters
are the new characters interjected into the string.
REPLACE function to replace existing characters of all occurrences. Using this syntax
REPLACE(string_expression, search_string, replacement_string), where every incidence
of search_string found in the string_expression will be replaced with
replacement_string. Using query analyzer, name 3 ways to get an accurate count of the
number of records in a table?
SELECT * FROM table1 SELECT COUNT(*) FROM table1
SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2
How to rebuild the Master Database?
This is one of the frequently asked SQL Server Questions. Shutdown Microsoft SQL
Server 2000, and then run Rebuildm.exe. This is located in the Program Files\Microsoft
SQL Server\80\Tools\Binn directory.
In the Rebuild Master dialog box, click Browse. In the Browse for Folder dialog box, select
the \Data folder on the SQL Server 2000 compact disc or in the shared network directory
from which SQL Server 2000 was installed, and then click OK.
Advertisements
Click Settings. In the Collation Settings dialog box, verify or change settings used for the
master database and all other databases.
Initially, the default collation settings are shown, but these may not match the collation
selected during setup. You can select the same settings used during setup or select new
collation settings. When done, click OK.
In the Rebuild Master dialog box, click Rebuild to start the process. The Rebuild Master
utility reinstalls the master database. To continue, you may need to stop a server that is
running.
What are the basic functions for master, MSDB, model, TEMPFB
databases?
This is one of the frequently asked SQL Server Interview
Questions. The Master database holds information for all databases located on the SQL
Server instance and is the glue that holds the engine together. Because SQL Server
cannot start without a functioning master database, you must administer this database
with care.
The MSDB database stores information regarding database backups, SQL Agent
information, DTS packages, SQL Server jobs, and some replication information such as
for log shipping.
The TEMPDB holds temporary objects such as global and local temporary tables and
stored procedures. The model is essentially a template database used in the creation of
any new user database created in the instance.
What is De-normalization?
De-normalization is the process of attempting to optimize the performance of a database
by adding redundant data. It is sometimes necessary because current DBMSs implement
the relational model poorly. A true relational DBMS would allow for a fully normalized
database at the logical level while providing physical storage of data that is tuned for high
performance. De-normalisation is a technique to move from higher to lower normal forms
of database modeling in order to speed up database access.
What is Scheduled Jobs or What is a Scheduled Tasks?
This is one of the frequently asked SQL Server Interview Questions. Scheduled tasks let
users automate processes that run on regular or predictable cycles. Users can schedule
administrative tasks, such as cube processing, to run during times of slow business
activity. Users can also determine the order in which tasks run by creating job steps within
a SQL Server Agent job. E.g. Back up the database, Update the Stats of Tables. Job steps
give the user control over the flow of execution.
If one job fails, the user can configure SQL Server Agent to continue to run the remaining
tasks or to stop the execution.
Advertisements
CNAME VARCHAR(50),
BALANCE MONEY,
CITY VARCHAR(50)
)
Table Level Imposing a Constraint:
CREATE TABLE CUSTOMER
CUSTID INT,
CNAME VARCHAR(50),
BALANCE MONEY,
CITY VARCHAR(50),
)
What is a composite constraint in SQL Server?
There is no difference in behavior whether the constraint is imposed at table level or
column level but if a constraint is imposed at table level we have the advantage of
imposing composite constraints. That is one constraint on multiple columns. For
example:
CREATE TABLE BRANCHDETAILS
CITY VARCHAR(50),
BRANCHCODE VARCHAR(10),
)
Note: The drawback with a NOT NULL constraint is it will allow duplicate values whereas
in the case of the UNIQUE constraint it will allow null values.
What is CHECK Constraint in SQL Server?
1. The CHECK constraint is used to enforce domain integrity.
2. Domain integrity ensures that the values going to store in a column must
follow some defined rules such as range, type, and format.
3. In simple words, we can say that Domain Integrity enforces valid entries
for a given column by restricting the type, the format, or the range of
possible values.
4. Check constraints allow us to define an expression for a TABLE that must
not evaluate to FALSE for a data modification statement to succeed.
Example:
CREATE TABLE EMPLOYEE
(
EMP_ID INT NOT NULL PRIMARY KEY CHECK(EMP_ID BETWEEN 0 AND 1000),
)
Check constraints will be useful to limit the range of possible values in a column.
Advertisements
FOR INSERT
AS
BEGIN
END
Let’s insert one record: INSERT INTO EMPLOYEE VALUES(106,’FF’, 30000, ‘UP’)
What is Deleted Magic Table in SQL Server?
This table is created when we perform a delete operation providing access to the record
being deleted. Whenever we delete a record from a table the record information can view
with the deleted magic table like below.
CREATE TRIGGER T2 ON EMPLOYEE
FOR DELETE
AS
BEGIN
END
Let’s delete one record: DELETE FROM EMPLOYEE WHERE EID = 105
What is a DML Trigger in SQL Server?
DML stands for Data Manipulation Language. INSERT, UPDATE, and DELETE
statements are DML statements. The DML triggers are fired whenever data is modified
using INSERT, UPDATE, and DELETE events.
These DML Triggers execute when the user tries to modify or change data through data
manipulation language events such as INSERT, UPDATE and DELETE statements on
the table or view.
DML Triggers can be used to enforce business rules and data integrity. DML triggers are
similar to constraints in the way they enforce integrity.
Syntax:
FOR UPDATE
AS
BEGIN
END
Let’s delete one record
UPDATE EMPLOYEE SET ENAME =’PRANAYA’ WHERE EID = 101
What are DDL triggers in SQL Server?
DDL triggers fire in response to DDL events – CREATE, ALTER, and DROP (Table,
Function, Index, Stored Procedure, etc…).
The DDL triggers fires in response to a variety of data definition language events such as
Create, Alter, Drop, Grant, Denay and Revoke. The DDL triggers are introduced from SQL
Server 2005 version which will be used to restrict DDL operations such as CREATE,
ALTER and DROP commands.
A DDL trigger is a special type of stored procedure that executes in response to a server
scoped or database scoped events. DDL triggers fire only after the DDL statements
execute so we cannot use “InsteadOf Triggers” here and moreover DDL triggers will not
fire in response to events that affect local temporary tables.
Syntax:
CREATE TRIGGER <TRIGGER NAME>
AS
BEGIN
<TRIGGER BODY/ STATEMENTS>
END
<Event_Type> refers to the event that will fire the trigger which can be anything like
Create_Table, Drop_Table, Alter_Table, etc.
What is the use of DDL triggers in SQL Server?
If we want to execute some code in response to a specific DDL event. To prevent certain
changes to our database schema. Audit the changes that the users are making to the
database structure
How to Enable, Disable and Drop Triggers in SQL Server?
To disable the trigger:
1. Right-click on the trigger in object explorer and select “Disable” from the
context menu
2. We can also disable the trigger using the following T-SQL
command: DISABLE TRIGGER trMyFirstTrigger ON DATABASE
To enable the trigger:
1. Right-click on the trigger in object explorer and select “Enable” from the
context menu
2. We can also enable the trigger using the following T-SQL
command: ENABLE TRIGGER trMyFirstTrigger ON DATABASE
To drop trigger:
1. Right-click on the trigger in object explorer and select “Delete” from the
context menu
2. We can also drop the trigger using the following T-SQL command: DROP
TRIGGER trMyFirstTrigger ON DATABASE
SQL Server Views Interview Questions and Answers
In this article, I am going to discuss the most frequently asked SQL Server Views
Interview Questions and Answers. Please read our previous article where we discussed
the most frequently asked SQL Server Triggers Interview Questions with Answers. As
part of this article, we are going to discuss the following SQL Server Views Interview
Questions with answers.
Advertisements
1. What is a View in SQL Server?
2. What are the differences between a table and a view in SQL
Server?
3. How many types of views are there in SQL Server?
4. What is a simple view or Updatable view?
5. What is a complex View in SQL Server?
6. Can we drop a table that has dependent views on it?
7. Can we create a view based on other views?
8. Can we update the views in SQL Server?
9. Why do we need Views in SQL Server?
10. What are the advantages of using views? OR when do you usually
use views?
11. What are indexed views? Or What are materialized views?
12. What are the limitations of a View in SQL Server?
What is a View in SQL Server?
A view is nothing more than a saved SQL query. A view can also be considered as a
virtual table. So, we can think of a view either as a compiled SQL query or a virtual table.
As a view represents a virtual table it does not physically store any data by default. When
we query a view we actually, retrieve the data from the underlying database tables.
What are the differences between a table and a view?
When compared with a table we have the following differences between a table and view.
1. The table is physical and the view is logical
2. A table is an independent object whereas view is a dependent object that
is a view depends on a table or tables from which it is loading the data.
3. When a new table is created from an existing table the new and old tables
are independent themselves that is the changes of one table will not be
reflected into the other table whereas if a view is created based on a table
any changes that are performed on the table reflects into the view and any
changes performed on the view reflected in the table also.
Instead of using the INNER JOIN keyword we can just use the JOIN keyword as shown
below. JOIN or INNER JOIN means the same.
SELECT Cand.CandidateId,
Cand.FullName,
Cand.CompanyId,
Comp.CompanyId,
Comp.CompanyName
FROM Candidate Cand
JOIN Company Comp
ON Cand.CompanyId = Comp.CompanyId
What is the Left Outer Join in SQL Server? Explain with an example?
Let us understand Left join in SQL Server with an example. If we want to select all the
rows from the LEFT table (In our example Candidate Table) including the rows that have
a null foreign key value (CompanyId in Candidate Table is the foreign key ) then we
use LEFT OUTER JOIN. A query involving a LEFT OUTER JOIN for the Candidate and
Company Table is shown below.
SELECT Cand.CandidateId,
Cand.FullName,
Cand.CompanyId,
Comp.CompanyId,
Comp.CompanyName
FROM Candidate Cand
LEFT OUTER JOIN Company Comp
ON Cand.CompanyId = Comp.CompanyId
If we run the above query the output will be as shown below. If we look at the output, we
now got all 7 rows (all the rows from the Candidate Table) including the row that has a null
value for the CompanyId column in the Candidate Table. So, the LEFT OUTER JOIN
would get all the rows from the LEFT Table including the rows that have null foreign key
value.
Instead of using the LEFT OUTER JOIN keyword we can just use the LEFT JOIN keyword
as shown below. LEFT OUTER JOIN or LEFT JOIN means the same.
SELECT Cand.CandidateId,
Cand.FullName,
Cand.CompanyId,
Comp.CompanyId,
Comp.CompanyName
FROM Candidate Cand
LEFT JOIN Company Comp
ON Cand.CompanyId = Comp.CompanyId
What is the Right Outer Join in SQL Server? Explain with an example?
Let us understand Right Outer join in SQL Server with an example. If we want to select
all the rows from the LEFT Table (In our example Candidate Table) that have non-null
foreign key values plus all the rows from the RIGHT table (In our
example Company Table) including the rows that are not referenced in the LEFT Table,
then we use RIGHT OUTER JOIN. A query involving a RIGHT OUTER JOIN for
the Candidate and Company Table is shown below.
SELECT Cand.CandidateId,
Cand.FullName,
Cand.CompanyId,
Comp.CompanyId,
Comp.CompanyName
FROM Candidate Cand
RIGHT OUTER JOIN Company Comp
ON Cand.CompanyId = Comp.CompanyId
If we run the above query the output will be as shown below. If we look at the output, we
now got 6 rows. All the rows from the Candidate Table that has non-null foreign key value
plus all the rows from the Company Table including the row that is not referenced in
the Candidate Table.
Instead of using the RIGHT OUTER JOIN keyword we can just use the RIGHT JOIN
keyword as shown below. RIGHT OUTER JOIN or RIGHT JOIN means the same.
SELECT Cand.CandidateId,
Cand.FullName,
Cand.CompanyId,
Comp.CompanyId,
Comp.CompanyName
FROM Candidate Cand
RIGHT JOIN Company Comp
ON Cand.CompanyId = Comp.CompanyId
What is Full Outer Join in SQL Server? Explain with an example?
Let us understand Full Outer join in SQL Server with an example. If we want to select all
the rows from the LEFT Table (In our example Candidate Table) plus all the rows from
the RIGHT table (In our example Company Table), then we use FULL OUTER JOIN. A
query involving a FULL OUTER JOIN for the Candidate and Company Table is shown
below.
SELECT Cand.CandidateId,
Cand.FullName,
Cand.CompanyId,
Comp.CompanyId,
Comp.CompanyName
FROM Candidate Cand
FULL OUTER JOIN Company Comp
ON Cand.CompanyId = Comp.CompanyId
If we run the above query the output will be as shown below. If you look at the output, we
now got 8 rows. All the rows from the Candidate Table and all the rows from
the Company Table.
Instead of using FULL OUTER JOIN keyword we can just use FULL JOIN keyword as
shown below. FULL OUTER JOIN or FULL JOIN means the same.
SELECT Cand.CandidateId,
Cand.FullName,
Cand.CompanyId,
Comp.CompanyId,
Comp.CompanyName
FROM Candidate Cand
FULL JOIN Company Comp
ON Cand.CompanyId = Comp.CompanyId
The following procedure returns the total number of employees from the Employee table,
using the output parameter i.e. @TotalCount.
Create Procedure spGetTotalCountOfEmployees1
@TotalCount int output
As
Begin
Select @TotalCount = COUNT(ID)
From tblEmployee
End
Executing spGetTotalCountOfEmployees1 returns 6.
Declare @TotalEmployees int
Execute spGetTotalCountOfEmployees @TotalEmployees Output
Select @TotalEmployees
Re-written stored procedure using return variables
Create Procedure spGetTotalCountOfEmployees2
As
Begin
return (Select COUNT(ID)
From Employees)
End
Executing spGetTotalCountOfEmployees2 returns 6.
Declare @TotalEmployees int
Execute @TotalEmployees = spGetTotalCountOfEmployees2
Select @TotalEmployees
So, we are able to achieve what we want using output parameters as well as return values.
Now let’s look at an example where return status variables cannot be used, but Output
parameters can be used.
In this stored procedure, we are retrieving the name of the employee based on their Id
using the output parameter i.e. @Name.
Create Procedure spGetNameById1
@Id int,
@Name nvarchar(20) Output
As
Begin
Select @Name = Name
From tblEmployee
Where Id = @Id
End
Executing the spGetNameById1 procedure will print the name of the employee
Declare @EmployeeName nvarchar(20)
Execute spGetNameById1 3, @EmployeeName out
Print ‘Employee name: ‘ + @EmployeeName
Now let’s try to do the same thing using the return status variables.
Create Procedure spGetNameById2
@Id int
As
Begin
Return (Select Name
From tblEmployee
Where Id = @Id)
End
When we execute the spGetNameById2 stored procedure, it will return an error
stating ‘Conversion failed when converting the nvarchar value ‘Sam’ to data type
int.’. The return status variable is an integer, and hence when we select the name of an
employee and try to return that we get the above conversion error.
Declare @EmployeeName nvarchar(20)
Execute @EmployeeName = spGetNameById2 1
Print ‘Employee name: ‘ + @EmployeeName
So using return values we can only return integers and that too, only one integer. It is not
possible, to return more than one value using return values, whereas output parameters,
can return any data type and a stored procedure can have more than one output
parameter.
In general, RETURN values are used to indicate the success or failure of the
stored procedure, especially when we are dealing with nested stored procedures. The
return value of 0, indicates success, and any nonzero value indicates failure.
Explain the Disadvantages of Return status value.
1. We cannot return more than one value using the return status variable in
SQL Server.
2. It is not possible to return values other than an integer using the return
status variable in SQL Server Stored Procedure.
We can overcome the above two problems using the output variables in SQL Server
Stored Procedure.
What are the advantages of using a stored procedure in SQL
Server?
This SQL Server Stored Procedure Interview Questions asked in almost all
interviews. The following are the advantages of using Stored Procedures over inline SQL
queries in SQL Server.
Execution Plan Retention and Reusability
As there is no unnecessary compilation of queries this will reduces the burden on
database (when we send a query to a SQL Server three things happen in order, 1st it
checks the syntax of that query, 2nd it compiles that query, 3rd it generates an execution
plan) as response User will get a quick response. Let’s get into more details.
The Stored Procedures are pre-compiled and their execution plan is cached and
used again when the same stored procedure is executed again. Although ad-hoc queries
also create and reuse plan, the plan is reused only when the query is the textual match
and the datatypes are matching with the previous call. Any changes in the datatype or you
have an extra space in the query then, a new plan is created.
Reduces the Network Traffic
The Stored Procedure reduces network traffic. When we execute a stored procedure we
need to send the procedure name and parameters so only these things are passed on the
network but if we are not using the stored procedure then we need to write the ad-hoc
queries and we need to execute them which may contain many numbers of lines. So the
stored procedure reduces the network traffic as a result performance of the application
increase.
Code Reusability and Better Maintainability
Multiple applications can use the same stored procedure. The different applications which
want similar kind of data then they can use the same stored procedure. The advantage is
that if we want to change the stored procedure then we need to change it in one place that
will affect to all the application that uses it whereas if it is inline SQL query and if we have
to use it in multiple applications, then we end up with multiple copies of the same inline
SQL query, and if the logic has to change, then we have to change the logic at all the
places, which makes it harder maintaining inline SQL. So, the stored procedure provides
code reusability and maintainability.
Better Security
By granting permission to the underlying database the user can do everything. He can
view all the records as well as he can also modify the records. But if we want to restrict
the user only to view the records then we need to grant only for that stored procedure
which will display the records. In that way, we achieve better security with a
stored procedure.
Using a stored procedure we can also avoid the SQL Injection attack.
What is an execution plan?
An execution plan is nothing but for the query to execute, what are the best possible ways
available and it will choose the best possible way based on the indexes that available on
the SQL Server to help that query. Based on those it generates the execution plan and
then it executes the query. It will increase the performance of the application.
What is an execution plan? When would you use it? How would you
view the execution plan?
An execution plan is basically a roadmap that graphically or textually shows the data
retrieval methods chosen by the SQL Server query optimizer for a stored procedure or ad-
hoc query and is a very useful tool for a developer to understand the performance
characteristics of a query or stored procedure since the plan is the one that SQL Server
will place in its cache and use to execute the stored procedure or query. From within Query
Analyser is an option called “Show Execution Plan” (located on the Query drop-down
menu). If this option is turned on it will display the query execution plan in the separate
window when the query is run again.
How to view the text of the stored procedure?
Use system stored procedure sp_helptext <user defined stored procedure name>
Ex: sp_helptext spGetEmployeeByGenderAndDepartment
Right-click on the stored procedure in object explorer => Script procedure as =>Create To
=> new query editor window
How to encrypt the text of a stored procedure?
To encrypt the text of a stored procedure we use WITH ENCRYPTION option. For
example
CREATE PROCEDURE SPWELCOME
WITH ENCRYPTION
AS
BEGIN
PRINT 'WELCOME TO PROCEDURE'
END
Now it is not possible to view the text of this encrypted procedure.
What are the different procedure attributes in SQL Server?
This is one of the frequently asked SQL Server Stored Procedure Interview
Questions. There are two types of attributes
1. The With Encryption
2. With Recompile
With Encryption Attribute:
If this attribute is used on the procedure the text of this procedure is encrypted and will not
be shown in the text column of the syscomments table so no one will be having an option
to view the content of it.
Note: When an application is developed for a client at the time of installing this application
on the client system we will be using the encryption option on all the views, procedures,
functions, triggers, etc. and install on the client machine. So that they will not have the
chance of viewing the source code or altering the source code.
With Recompiled Attribute:
1. Whenever a procedure is compiled for the first time it prepares the best
query plan according to the current state of the database and executes the
query plan when the procedure is called.
2. The compilation of the procedure and preparing a query plan is prepared
not only at the time of procedure creation but each and every time the server
is restarted (Implicitly occurs).
3. If the procedure is created by using with Recompile procedure attribute, it
is forced to be compiled each time it is executed and whenever it compiles
it prepares the query plan.
4. Forcing a procedure for recompilation and prepared a query plan is
required when the database undergoes significant changes to its data or
structure.
5. Another reason to force a procedure to recompile is if at all the tables is
added with new indexes from which the procedure might be benefited
forcing for recompilation is very important because we cannot wait until the
server is restarted for preparing a new query plan.
Note: Even if the With Recompile option is available it is not suggested to be used if at all
there are no significant changes in the structure of the databases.
What is the temporary stored procedure?
The stored procedures which are created temporarily in a database (not stored
permanently) is called as the temporary stored procedure.
There are two types of temporary stored procedures such as
1. Private / Local Temporary Stored Procedure
2. Public / Global Temporary Stored Procedure.
What are Private / Local Temporary Stored Procedure?
1. These are created with the # prefix added to the procedure name.
2. Private or Local Temporary Stored Procedures are executed by the
connection that created it.
3. These are automatically deleted when the connection created is closed.
Syntax: The syntax for creating a local temporary procedure
CREATE PROCEDURE #<PROCEDURE NAME>
AS
BEGIN
<PROCEDURE BODY / STATEMENTS / QUERIES>
END
Example: Create a Local Temporary stored procedure.
CREATE PROCEDURE #DelRec
AS
BEGIN
Delete from EMPLOYEE where Eid = 105
END
This procedure is executed on the session which is created it and once the session is
closed this procedure is automatically deleted. And we cannot access this procedure once
the session is closed also we cannot access this procedure from another session.
What is the Public / Global Temporary Stored Procedure?
1. These are created with the ## prefix added to the procedure name.
2. Any connection can execute the global temporary stored procedure.
3. A Global Temporary Stored Procedure exists until the connection used by
the user who created the procedure is closed and any currently executing
versions of the procedure by any other connections are implemented.
4. Once the connection that was used to create the procedure is closed, no
further execution of the Global Temporary Stored Procedure is allowed.
Only those connections that have already started executing the stored
procedure are allowed to complete.
Syntax: The syntax for creating a Global Temporary Procedure
CREATE PROCEDURE ##<PROCEDURE NAME>
AS
BEGIN
<PROCEDURE BODY / STATEMENTS / QUERIES>
END
Example: Create a Local Temporary stored procedure.
CREATE PROCEDURE ##DelRec
AS
BEGIN
Delete from EMPLOYEE where Eid = 105
END
What is the use of a Temporary Stored Procedure?
Temporary Stored Procedures are useful when connecting to earlier versions of SQL
Server that do not support the reuse of execution plans for Transact-SQL statements or
batches.
Example: Procedure with a default value.
CREATE PROCEDURE PROC3(@X INT= 100, @Y INT)
AS
BEGIN
DECLARE @Z INT
SET @Z=@X+@Y
PRINT'The SUM of the 2 Numbers is: '+CAST(@Z AS VARCHAR)
END
Executing the above procedure:
1. EXEC PROC3 200, 25
2. EXEC PROC3 @X=200, @Y=25
3. EXEC PROC3 @X=DEFAULT, @Y=25
4. EXEC PROC3 @Y=25
In the 3rd and 4th case, it uses the default value of 100 to the variable X which has been
given while creating the procedure.
What is deferred name resolution in SQL Server?
This is one of the most frequently asked SQL Server Stored Procedure Interview Question
in SQL Server Interview. Let me explain deferred name resolution with an example.
Consider the stored procedure shown below.
Advertisements
config.Formatters.Add(new CustomJsonFormatter());
With these 2 changes, when a request is issued from the browser you will get JSON
formatted data and the Content-Type header of the response is also set to
application/json. If you are using tools like a fiddler and if you set Accept header to
application/xml you will still get XML formatted data.
1) What is data structure?
Data structure refers to the way data is organized and manipulated. It seeks to
find ways to make data access more efficient. When dealing with the data
structure, we not only focus on one piece of data but the different set of data
and how they can relate to one another in an organized manner.
7) What is LIFO?
LIFO is a short form of Last In First Out. It refers how data is accessed, stored
and retrieved. Using this scheme, data that was stored last should be the one
to be extracted first. This also means that in order to gain access to the first
data, all the other data that was stored before this first data must first be
retrieved and extracted.
8 ) What is a queue?
A queue is a data structure that can simulate a list or stream of data. In this
structure, new elements are inserted at one end, and existing elements are
removed from the other end.
9) What are binary trees?
A binary tree is one type of data structure that has two nodes, a left node, and
a right node. In programming, binary trees are an extension of the linked list
structures.
AVL tree
Introduction to ADO.NET
ADO.NET is a technology used for data and is provided by the Microsoft .NET
Framework. It is a part of the .NET framework that supports the communication
between relational and non-relational systems with the help of a set of software
components. It supports disconnected architecture using which programmers are
allowed to access data and data services from a database without depending on the
data source.
ADO.NET is comprised of a group of built-in classes that are useful for establishing
the database connection, for gaining access to XML, relational data, and application
data, and for retrieval of a result. It can be used in various programming languages
such as Visual Basic.NET, Visual C++, etc., that are supported by the .NET
framework.
Advantages of ADO.NET
ADO.NET has various advantages which can be categorized into the following
categories:
• Interoperability: It provides the ability to communicate across heterogeneous
environments, once the connection has been established between them.
• Scalability: It provides the ability to serve an increasing number of clients without
reducing the performance of the system. So we can say that ADO.NET is highly
scalable because it is flexible enough to be easily expanded when there is a
requirement for the same.
• Productivity: It provides the ability to rapidly develop robust applications for data
access using rich and extensible component object models provided by the ADO.NET.
• Performance: An improvement over earlier ADO.NET versions because of the
disconnected data model. It can establish connections quickly to fetch data without
any delay.
Scope of ADO.NET
work in order to have a good scope. Any full-stack developer who has a better grip
over both front-end and back-end technology can precisely learn ADO.NET.
• ADO.NET stands for ActiveX Data Object, it is a part of the .NET Framework by
Microsoft. ADO.NET framework provides a set of classes that are used to handle
data communication with data sources such as XML files and databases (such as
SQL, Oracle, MySQL, MS Access, etc.).
• ADO.NET can separate mechanisms for data connectivity, data access, and data
manipulation.
• It has introduced the disconnected architecture, in which data can be stored in a
DataSet. ADO.NET has providers for database connection, commands for execution,
and result retrieval.
• The ADO.NET classes are stored in the DLL named System.Data.dll.
• Various applications like ASP.NET applications, console applications, windows
applications, etc., will use ADO.NET for database connection, command execution,
and retrieval of data.
• The DataSet is a collection of database tables(row and column format) that contain
the data. It is helpful for fetching the data without any need for Data Source
interaction, that is why it is called a disconnected data access method.
• It is an in-memory data store that can contain multiple tables at the same time.
DataRelation objects can be used to relate these tables.
• For creating a DataSet object, ADO.NET provides a DataSet class that consists of
constructors and methods to carry out data-related operations.
• It can be used with various data sources, with XML data, or to manage the
application’s local data. The DataSet will include related tables, data constraints, and
relationships among the tables.
It works in connected mode to access the It does require an active connection, works in
data store. disconnected mode to access the data store.
It uses the RecordSet object to access and It uses a DataSet object to access and store data
store data from the data sources. from the data sources.
Using a single connection instance, it is not Using a single connection instance you can send
possible to send multiple transactions. multiple transactions.
ADO ADO.NET
using System;
using System.Data.SqlClient;
using System.Data;
namespace DataAdapterExample
{
public partial class DataAdapterDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("data source=.; database=items; integrated
security=SSPI"))
{
SqlDataAdapter da = new SqlDataAdapter("Select * from items", conn);
DataSet s = new DataSet();
da.Fill(s);
GridView1.DataSource = s;
GridView1.DataBind();
}
}
}
}
Here, DataAdapter will receive the data from the items table and fill the DataSet,
which will be later used to display the information retrieved from the items
database.
It is a technology useful for accessing data from It is a technology useful for the creation
databases. of dynamic web pages.
It is used to develop reliable and scalable It is used to create dynamic web pages,
database applications with high performance for web applications, websites, and web
client-server applications. services.
DataSet can be said as a collection of database tables(row and column format) that
holds the data. There are two types of DataSet in ADO.NET. They are:
1. Typed DataSet: A typed DataSet is derived from the DataSet base class and can be
created by selecting the DataSet option provided by Visual Studio. It will be created
as an XML schema(.xsd file) that contains DataSet structure information such as
rows, columns, and tables. Data from the database is moved into a dataset and from
the dataset to another component in the XML format.
2. Untyped DataSet: Untyped DataSet does not have an associated XML schema with
it. Users are supposed to add columns, tables, and other elements to it. Properties
can be set during design time or can add them during run time.
using System;
using System.Data.SqlClient;
using System.Data;
namespace DataSetDemo
{
public partial class DataSetExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("data source=.; database=employee;
integrated security=SSPI"))
{
SqlDataAdapter da = new SqlDataAdapter("Select * from employee", conn);
DataSet d = new DataSet();
da.Fill(d);
GridView1.DataSource = d;
GridView1.DataBind();
}
}
}
}
Here, DataSet will be filled by DataAdapter that receives data from the employee
table. This DataSet will be used to display the information received from the
employee database.
UniqueConstraint and
UniqueConstraint and ForeignKeyConstraint
ForeignKeyConstraint objects are not
objects are available for enforcing data integrity.
available enforcing data integrity.
1. System.Data: It contains the definition for rows, columns, relations, views, tables,
constraints, and databases.
2. System.Data.SqlClient: It is a collection of classes that are helpful in connecting to a
Microsoft SQL Server database such as SqlConnection, SqlCommand,
SqlDataAdapter, etc.
3. System.Data.Odbc: It consists of classes that are required for connecting with most
Odbc Drivers. These classes include OdbcConnection, OdbcCommand.
4. System.Data.OracleClient: It has classes required for connection with an Oracle
database, OracleConnection, OracleCommand.
Object pooling is a repository of the objects in memory that can be reused later
without creating them. This object pooling reduces the burden of creating objects
when it is required. Whenever there is a requirement of an object, the object pool
manager will process the request and serve accordingly. It is designed for optimizing
the use of limited resources so that the demands of client requests will be fulfilled.
It supports various database tables from different It supports only a single table from a
databases. single database.
• ExecuteScalar(): This method returns only a single value from the first row and first
column of the ResultSet after the execution of the query. Even if ResultSet is having
more than one row or column, all those rows and columns will be ignored. If the
ResultSet is empty, it will return NULL.
• ExecuteNonQuery(): This method returns the number of rows affected by the
execution of a query. This method is not useful to return the ResultSet.
• ExecuteReader(): This method returns an object of DataReader which is a read-only
and forward-only ResultSet. It needs a live connection with the Data Source. We
cannot directly instantiate the DataReader object. A valid DataReader object can be
created with the help of the ExecuteReader() method.
• ExecuteXmlReader(): This method builds an object of the XmlReader class and will
return the ResultSet in the form of an XML document. This method is made
available in SQL Server 2000 or later.
In ADO.NET, transactions are used when you want to bind several tasks together
and execute them in the form of a single unit. The transaction provides data
consistency by ensuring either all of the database operations will be succeeded or
all of them will be failed. For example, consider an application that performs two
tasks. First, it updates an item_order table with order information. Second, it
updates an item_inventory table that holds inventory information, where a number
of items ordered will be debited. If any one of the tasks fails, then both updates
must be rolled back.
• Local Transaction:
o A local transaction is a single-phase transaction that is directly handled by
the database. Every .NET Framework data provider has its own Transaction
object for bringing out local transactions.
o For example, if we want to perform a transaction using SQL Server database,
we import a System.Data.SqlClient namespace. Similarly, to perform an Oracle
transaction, import the System.Data.OracleClient namespace.
A DbTransaction class will be used for writing code that is independent of the
provider and that requires transactions.
• Distributed Transaction:
o A distributed transaction is coordinated by a transaction monitor and will
make use of fail-safe mechanisms like two-phase commit for transaction
resolution. This transaction will affect multiple resources.
o If the user can make use of a distributed transaction, if he wants to do a
transaction across multiple data servers such as Oracle, SQL Server, etc.
o If you want a distributed transaction to commit, all participants must
guarantee that data modification made will be permanent. Changes must
remain unchanged even if the system crash or other unforeseen events
occur. Even if a single participant will make this guarantee fail, then the
entire transaction will fail, and updates made to data within the transaction
scope are rolled back.
13. Explain the difference between OLEDB (Object Linking and Embedding
DataBase) and ODBC (Open DataBase Connectivity).
OLEDB ODBC
It is procedural-based. It is component-based.
make connection with OLE DB data source. On success, this function will return a
source. connection resource handle that is helpful in
accessing the database using subsequent
commands.
• Data binding in ADO.NET is the process through which user interface (UI) controls
of a client application are configured to update or fetch data from data sources like
a database or XML document. Using data binding, the user will be able to bind
values to the particular control.
• There are two types of data binding based on the type of binding offered:
1. Simple data binding: It is the process of binding the control with only one
value in the dataset. The controls such as label, text box will be made bound
to the control using the control properties.
2. Complex data binding: It is the method of binding the component with the
Database. The controls can be a Dropdown list, GridView, or combo box.
One or more than one value can be displayed from the dataset using the
complex data binding.
The task of grouping database connections in the cache memory is to make them
available whenever there is a requirement of connection. Opening a new database
connection every time is a time-consuming process. Connection pooling allows you
to reuse existing and active database connections, whenever there is a need, and
thus increases the application performance.
By setting the pooling property into true or false in the connection string, we can
enable or disable the connection pooling in the application. It is enabled by default
in every application.
The SQL connection and SQL command object will be created. We pass the SQL
query to the object of the SQL command class. A new data table object will be
created by using the DataTable class and it is filled with data using a data adapter.
17. Name some of the properties and methods provided by the DataReader in
ADO.NET?
• Read(): This method reads a record from the SQL Server database.
• Close(): It closes a SqlDataReader object.
• NextResult(): It moves the data reader to the next result during the time of batch
transactions.
• Getxxx(): Various types of Getxxx() methods such as GetBoolean(Int32),
GetChar(Int32), GetFloat(Int32), GetDouble(Int32), etc., are provided by the
DataReader. These methods will read a value of a particular data type from a
column. For example, GetFloat() will return a column value as a Float and GetChar as
a character.
• There must be several processes with the same parameters and security settings so
that they can share the same connection.
• The connection string should be identical.
Data providers are used to transferring the data between the client application and
the data store. It encapsulates the database-specific details. Data providers are
helpful for database connection, data retrieval, storing the data in a dataset, reading
the retrieved data, and updating the database.
The data providers that comes along with the ADO.NET Framework are:
• OLE DB: The OLEDB provider is available under System.Data.OleDb namespace. This
provider can be used to access Microsoft Access, DB2/400, SyBase, and SQL Server
6.5 and earlier.
• ODBC: The ODBC provider is available under System.Data.Odbc namespace. This
provider is used when there will not be any newer provider is available.
• SQL Server: The Microsoft SQL Server provider is available
under System.Data.SqlClient namespace. Classes available under this provider will
provide the same functionality as the generic OLEDB provider.
The reasons for using Stored Procedures in ADO.NET are given below:
• For improved performance
• For security reasons
• Easier to use and maintain
• Lesser Network Traffic
• Execution time is less
• Data Provider: It provides data to all the applications that perform the database
updates. The application can access data through the DataSet or DataReader object.
A data provider is a having group of components such as Command, Connection,
DataReader, and DataAdapter objects. Command and Connection objects are the
necessary components irrespective of the operations like Insert, Delete, Select, and
Update.
• Connection: The connection object is needed to connect with the database such as
SQL Server, MySQL, Oracle, etc. To create a connection object, you must know
about where the database is located(Ex: IP address or machine name, etc.) and the
security credentials(Ex: user name and password-based authentication or windows
authentication).
• Command: The command object is the component where you will write the SQL
queries. Then by using the command object, execute the queries over the
connection. By using the command object and SQL queries, you will be able to fetch
the data or send the data to the database.
• DataReader: DataReader is a connected read-only RecordSet that is helpful in
reading the records in the forward-only mode.
• DataAdapter: The DataAdapter acts as a bridge between the dataset and command
object. It receives the data from the command object and puts it into the data set.
• DataSet: The DataSet is a disconnected RecordSet that can be browsed in both
forward and backward directions. We can also update the data using the dataset.
DataSet is filled by using DataAdapter.
• DataView Class: A DataView allows you to create various views of data from
DataTable, which can be used for data-binding applications. Using this, you can
display the table with different order of sorting or you can filter the data based on a
filter expression or by row state, etc.
• XML: It is possible to create an XML representation of a dataset. In the dataset’s
XML representation, data is represented in XML format and the database schema is
represented in XML Schema Definition(XSD) language.
2. Briefly explain connected and disconnected architecture of ADO.NET.
Connected Architecture:
• In connected architecture, the connection must be kept open for accessing the data
retrieved from the database. Connected architecture is based on Connection,
DataReader, Command, and Transaction classes.
• You constantly visit the database for any CRUD (Create, Read, Update, and Delete)
operation you want to do. This will create high traffic to the database, but this is
usually faster as you are doing only smaller transactions.
• DataReader can be said as a Connected Architecture as it holds the connection
open until it fetches all the rows one by one.
Disconnected Architecture:
• A single value from the first row and first column of the ResultSet will be returned
by ExecuteScalar() method on query execution.
• If the ResultSet is having multiple rows or columns, all those rows and columns will
be ignored except the first row and first column. If the ResultSet is empty, this
function will return NULL.
• The best situation to use ExecuteScalar() method is when we are using functions
such as COUNT(), SUM(), etc., as it uses only a few resources compared to the
ExecuteReader() method.
• Example:
Before performing any task in the database, SQL Server will authenticate. Two
types of authentication techniques are:
C#
"Server=MSSQL1;Database=Institute;Integrated Security=true;
C#
"Persist Security Info=False;User ID=Harsh;Password=xyz@123;Initial
Catalog=Institute;Server=MySqlServer"
6. What is Response.Expires and Response.ExpiresAbsolute property?
The above code can be used to add the required number of tables in a dataset. This
ensures connection-less access to data. As the dataset is filled with multiple tables,
every time we want to query the data the database connection is not required. It
also makes sure about the reusability of data.
High speed and performance are given by Disconnected methods are low in speed and
connected methods. performance.
It carries the single table data. It carries data from multiple tables.
We can’t update the data as it is read-only. Here we can update the data.
9. What is LINQ?
The DataSet object has two methods to track down the changes:
• GetChanges(): It returns the DataSet object that has been changed since it was
loaded or since the execution of the AcceptChanges() method.
• HasChanges(): It indicates if any modifications were made since from the time the
DataSet object was loaded or after a method call to the AcceptChanges() was made.
Use the RejectChanges() method, if you want to reverse the entire changes since
from the time the DataSet object was loaded.
• The method Clone() copies only the DataSet structure. The copied structure will
have all the constraints, relations, as well as DataTable schemas used by the
DataSet. It does not copy the data stored in the DataSet.
• The Copy() method copies the DataSet structure along with the data in the DataSet.
The original data will not be affected.
12. Which methods are provided to add or remove rows from the DataTable object?
The collection of rows for the DataTable object has been defined by the
DataRowCollection class. DataRowCollection class has the method NewRow() for
adding a new DataRow to DataTable. This method creates a new row that
implements the similar schema that is applied to the DataTable.
Consider the below example where a connection to the SQL Server has been
established. An employee database will be used to connect. The C# code will be:
Using block will be useful in closing the connection automatically. It is not required
to explicitly call the close() method, because using block will do this implicitly when
the code exits the block.
// ConnectionExample.cs
using System;
using System.Data.SqlClient;
namespace ConsoleApplicationExample
{
class ConnectionExample
{
static void Main(string[] args)
{
new Program().ConnectingMethod();
}
public void ConnectingMethod()
{
using (
// Creating Connection
SqlConnection conn = new SqlConnection("data source=.; database=employee;
integrated security=SSPI")
)
{
conn.Open();
Console.WriteLine("Connection Has Been Successfully Established.");
}
}
}
}
Output:
If the connection is not created with the help of using a block, a connection must be
closed explicitly.
14. What is serialization? Write an example program to serialize a DataSet.
Serialization is the method of converting an object into a byte stream which can be
stored as well as transmitted over the network. The advantage of serialization is
that data can be transmitted in a cross-platform environment across the network
and also it can be saved in a storage medium like persistent or non-persistent.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml.Serialization;
using System.IO;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=data_source_name;Initial
Catalog=employee;Integrated Security=True"); //Create connection object
SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn); //DataAdapter creation
DataSet s = new DataSet();
da.Fill(s);
FileStream fObj = new FileStream("C:\\demo.xml", FileMode.Create); // Create a XML file
XmlSerializer sObj = new XmlSerializer(typeof(DataSet));
sObj.Serialize(fObj, s); //Serialization of a DataSet
fObj.Close();
}
}
In the above given example, the database name is employee and, the table name is
emp. The data in a DataSet will be serialized and stored in a demo.xml file by using
Serialize() method.
15. Give an example code to fill the GridView by using the object of DataTable
during runtime.
using System;
using System.Data;
Output:
Conclusion
ADO.NET technology will definitely help in your career growth as it has quite a
good scope. Also learning this interesting technology will always be great fun.
ADO.NET along with the knowledge of databases will definitely be exceptional from
a growth perspective.
SQL pattern matching provides for pattern search in data if you have no clue as to
what that word should be. This kind of SQL query uses wildcards to match a string
pattern, rather than writing the exact word. The LIKE operator is used in
conjunction with SQL Wildcards to fetch the required information.
SELECT *
FROM students
WHERE first_name LIKE 'K%'
Use the NOT keyword to select records that don't match the pattern. This query
returns all students whose first name does not begin with K.
SELECT *
FROM students
WHERE first_name NOT LIKE 'K%'
Search for a student in the database where he/she has a K in his/her first name.
SELECT *
FROM students
WHERE first_name LIKE '%Q%'
The _ wildcard matches exactly one character of any type. It can be used in
conjunction with % wildcard. This query fetches all students with letter K at the
third position in their first name.
SELECT *
FROM students
WHERE first_name LIKE '__K%'
The _ wildcard plays an important role as a limitation when it matches exactly one
character. It limits the length and position of the matched results. For example -
Creating empty tables with the same structure can be done smartly by fetching the
records of one table into a new table using the INTO operator while fixing a
WHERE clause to be false for all records. Hence, SQL prepares the new table with a
duplicate structure to accept the fetched records but since no records get fetched
due to the WHERE clause in action, nothing is inserted into the new table.
A stored procedure that calls itself until a boundary condition is reached, is called a
recursive stored procedure. This recursive function helps the programmers to
deploy the same set of code several times as and when required. Some SQL
programming languages limit the recursion depth to prevent an infinite loop of
procedure calls from causing a stack overflow, which slows down the system and
may lead to system crashes.
Download PDF
Collation refers to a set of rules that determine how data is sorted and compared.
Rules defining the correct character sequence are used to sort the character data. It
incorporates options for specifying case sensitivity, accent marks, kana character
types, and character width. Below are the different types of collation sensitivity:
OLAP stands for Online Analytical Processing, a class of software programs that are
characterized by the relatively low frequency of online transactions. Queries are
often too complex and involve a bunch of aggregations. For OLAP systems, the
effectiveness measure relies highly on response time. Such systems are widely used
for data mining or maintaining aggregated, historical data, usually in multi-
dimensional schemas.
7. What is OLTP?
Real-Life Problems
Detailed reports
Attempt Now
The user-defined functions in SQL are like functions in any other programming
language that accept parameters, perform complex calculations, and return a value.
They are written to use the logic repetitively whenever required. There are two
types of SQL user-defined functions:
A UNIQUE constraint ensures that all values in a column are different. This provides
uniqueness for the column(s) and helps identify each row uniquely. Unlike primary
key, there can be multiple unique constraints defined per table. The code syntax for
UNIQUE is quite similar to that of PRIMARY KEY and can be used interchangeably.
Data Integrity is the assurance of accuracy and consistency of data over its entire
life-cycle and is a critical aspect of the design, implementation, and usage of any
system which stores, processes, or retrieves data. It also defines integrity
constraints to enforce business rules on the data when it is entered into an
application or a database.
As explained above, the differences can be broken down into three small factors -
• Clustered index modifies the way records are stored in a database based on the
indexed column. A non-clustered index creates a separate entity within the table
which references the original table.
• Clustered index is used for easy and speedy retrieval of data from the database,
whereas, fetching records from the non-clustered index is relatively slower.
• In SQL, a table can have a single clustered index whereas it can have multiple non-
clustered indexes.
4.5
100K+
Play Store
A database index is a data structure that provides a quick lookup of data in a column
or columns of a table. It enhances the speed of operations accessing data from a
database table at the cost of additional writes and memory to maintain the index
data structure.
CREATE INDEX index_name /* Create Index */
ON table_name (column_1, column_2);
DROP INDEX index_name; /* Drop Index */
There are different types of indexes that can be created for different purposes:
Unique indexes are indexes that help maintain data integrity by ensuring that no
two rows of data in a table have identical key values. Once a unique index has been
defined for a table, uniqueness is enforced whenever keys are added or changed
within the index.
Non-unique indexes, on the other hand, are not used to enforce constraints on the
tables with which they are associated. Instead, non-unique indexes are used solely
to improve query performance by maintaining a sorted order of data values that are
used frequently.
Clustered indexes are indexes whose order of the rows in the database corresponds
to the order of the rows in the index. This is why only one clustered index can exist
in a given table, whereas, multiple non-clustered indexes can exist in the table.
The only difference between clustered and non-clustered indexes is that the
database manager attempts to keep the data in the database in the same order as
the corresponding keys appear in the clustered index.
Clustering indexes can improve the performance of most query operations because
they provide a linear-access path to data stored in the database.
Cross join can be defined as a cartesian product of the two tables included in the
join. The table after join contains the same number of rows as in the cross-product
of the number of rows in the two tables. If a WHERE clause is used in cross join
then the query will work like an INNER JOIN.
Write a SQL statement to perform SELF JOIN for 'Table_X' with alias 'Table_1' and
'Table_2', on columns 'Col_1' and 'Col_2' respectively.
A self JOIN is a case of regular join where a table is joined to itself based on some
relation between its own column(s). Self-join uses the INNER JOIN or LEFT JOIN
clause and a table alias is used to assign different names to the table within the
query.
The SQL Join clause is used to combine records (rows) from two or more tables in a
SQL database based on a related column between the two.
There are four different types of JOINs in SQL:
• (INNER) JOIN: Retrieves records that have matching values in both tables involved
in the join. This is the widely used join for queries.
SELECT *
FROM Table_A
JOIN Table_B;
SELECT *
FROM Table_A
INNER JOIN Table_B;
• LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched
records/rows from the right table.
SELECT *
FROM Table_A A
LEFT JOIN Table_B B
ON A.col = B.col;
• RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the
matched records/rows from the left table.
SELECT *
FROM Table_A A
RIGHT JOIN Table_B B
ON A.col = B.col;
• FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the
left or right table.
SELECT *
FROM Table_A A
FULL JOIN Table_B B
ON A.col = B.col;
17. What is a Foreign Key?
Write a SQL statement to add a FOREIGN KEY 'col_fk' in 'table_y' that references
'col_pk' in 'table_x'.
18. What is a Subquery? What are its types?
A subquery is a query within another query, also known as a nested query or inner
query. It is used to restrict or enhance the data to be queried by the main query,
thus restricting or enhancing the output of the main query respectively. For
example, here we fetch the contact information for students who have enrolled for
the maths subject:
Write a SQL query to update the field "status" in table "applications" from 0 to 1.
Write a SQL query to select the field "app_id" in table "applications" where "app_id"
less than 1000.
Write a SQL query to fetch the field "app_name" from "apps" where "apps.id" is
equal to the above collection of "app_id".
The PRIMARY KEY constraint uniquely identifies each row in a table. It must
contain UNIQUE values and has an implicit NOT NULL constraint.
A table in SQL is strictly restricted to have one and only one primary key, which is
comprised of single or multiple fields (columns).
CREATE TABLE Students ( /* Create table with a single field as primary key */
ID INT NOT NULL
Name VARCHAR(255)
PRIMARY KEY (ID)
);
CREATE TABLE Students ( /* Create table with multiple fields as primary key */
ID INT NOT NULL
LastName VARCHAR(255)
FirstName VARCHAR(255) NOT NULL,
CONSTRAINT PK_Student
PRIMARY KEY (ID, FirstName)
);
write a sql statement to add primary key 't_id' to the table 'teachers'.
Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a' and
fields 'col_b, col_c'.
Constraints are used to specify the rules concerning data in the table. It can be
applied for single or multiple fields in an SQL table during the creation of the table
or after creating using the ALTER TABLE command. The constraints are:
• NOT NULL - Restricts NULL value from being inserted into a column.
• CHECK - Verifies that all values in a field satisfy a condition.
• DEFAULT - Automatically assigns a default value if no value has been specified for
the field.
• UNIQUE - Ensures unique values to be inserted into the field.
• INDEX - Indexes a field providing faster retrieval of records.
• PRIMARY KEY - Uniquely identifies each record in a table.
• FOREIGN KEY - Ensures referential integrity for a record in another table.
A table is an organized collection of data stored in the form of rows and columns.
Columns can be categorized as vertical and rows as horizontal. The columns in a
table are called fields while the rows can be referred to as records.
SQL stands for Structured Query Language. It is the standard language for relational
database management systems. It is especially useful in handling organized data
comprised of entities (variables) and relations between different entities of the data.
SELECT operator in SQL is used to select data from a database. The data returned is
stored in a result table, called the result-set.
Some common SQL clauses used in conjuction with a SELECT query are as follows:
• WHERE clause in SQL is used to filter records that are necessary, based on specific
conditions.
• ORDER BY clause in SQL is used to sort the records based on some field(s) in
ascending (ASC) or descending order (DESC).
SELECT *
FROM myDB.students
WHERE graduation_year = 2019
ORDER BY studentID DESC;
• GROUP BY clause in SQL is used to group records with identical data and can be
used in conjunction with some aggregation functions to produce summarized results
from the database.
• HAVING clause in SQL is used to filter records in combination with the GROUP BY
clause. It is different from WHERE, since the WHERE clause cannot filter
aggregated records.
The UNION operator combines and returns the result-set retrieved by two or more
SELECT statements.
The MINUS operator in SQL is used to remove duplicates from the result-set
obtained by the second SELECT query from the result-set obtained by the first
SELECT query and then return the filtered results from the first.
The INTERSECT clause in SQL combines the result-set fetched by the two SELECT
statements where records from one match the other and then returns this
intersection of result-sets.
Certain conditions need to be met before executing either of the above statements
in SQL -
• Each SELECT statement within the clause must have the same number of columns
• The columns must also have similar data types
• The columns in each SELECT statement should necessarily have the same order
Write a SQL query to fetch "names" that are present in either table "accounts" or in
table "registry".
Write a SQL query to fetch "names" that are present in "accounts" but not in table
"registry".
Write a SQL query to fetch "names" from table "contacts" that are neither present
in "accounts.name" nor in "registry.name".
A database cursor is a control structure that allows for the traversal of records in a
database. Cursors, in addition, facilitates processing after traversal, such as retrieval,
addition, and deletion of database records. They can be viewed as a pointer to one
row in a set of rows.
1. DECLARE a cursor after any variable declaration. The cursor declaration must
always be associated with a SELECT Statement.
2. Open cursor to initialize the result set. The OPEN statement must be called before
fetching rows from the result set.
3. FETCH statement to retrieve and move to the next row in the result set.
4. Call the CLOSE statement to deactivate the cursor.
5. Finally use the DEALLOCATE statement to delete the cursor definition and release
the associated resources.
Entity: An entity can be a real-world object, either tangible or intangible, that can be
easily identifiable. For example, in a college database, students, professors, workers,
departments, and projects can be referred to as entities. Each entity has some
associated properties that provide it an identity.
• One-to-One - This can be defined as the relationship between two tables where
each record in one table is associated with the maximum of one record in the other
table.
• One-to-Many & Many-to-One - This is the most commonly used relationship where
a record in a table is associated with multiple records in the other table.
• Many-to-Many - This is used in cases when multiple instances on both sides are
needed for defining a relationship.
• Self-Referencing Relationships - This is used when a table needs to define a
relationship with itself.
33. What is an Alias in SQL?
An alias is represented explicitly by the AS keyword but in some cases, the same can
be performed without it as well. Nevertheless, using the AS keyword is always a
good practice.
Write an SQL statement to select all from table "Limited" with alias "Ltd".
A view in SQL is a virtual table based on the result-set of an SQL statement. A view
contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.
35. What is Normalization?
Normal Forms are used to eliminate or reduce redundancy in database tables. The
different forms are as follows:
Students Table
Amanora Park Town Until the Day I Die (Emily Carpenter), Inception
Sara Ms.
94 (Christopher Nolan)
As we can observe, the Books Issued field has more than one value per record, and
to convert it into 1NF, this has to be resolved into separate individual records for
each book issued. Check the following table in 1NF form -
Sara Amanora Park Town 94 Until the Day I Die (Emily Carpenter) Ms.
Sara 24th Street Park Avenue Beautiful Bad (Annie Ward) Mrs.
A relation is in second normal form if it satisfies the conditions for the first normal
form and does not contain any partial dependency. A relation in 2NF has no partial
dependency, i.e., it has no non-prime attribute that depends on any proper subset
of any candidate key of the table. Often, specifying a single column Primary Key is
the solution to the problem. Examples -
Example 1 - Consider the above example. As we can observe, the Students Table in
the 1NF form has a candidate key in the form of [Student, Address] that can
uniquely identify all records in the table. The field Books Issued (non-prime
attribute) depends partially on the Student field. Hence, the table is not in 2NF. To
convert it into the 2nd Normal Form, we will partition the tables into two while
specifying a new Primary Key attribute to identify the individual records in the
Students table. The Foreign Key constraint will be set on the other table to ensure
referential integrity.
Here, WX is the only candidate key and there is no partial dependency, i.e., any
proper subset of WX doesn’t determine any non-prime attribute in the relation.
A relation is said to be in the third normal form, if it satisfies the conditions for the
second normal form and there is no transitive dependency between the non-prime
attributes, i.e., all non-prime attributes are determined only by the candidate keys of
the relation and not by any other non-prime attribute.
Example 1 - Consider the Students Table in the above example. As we can observe,
the Students Table in the 2NF form has a single candidate key Student_ID (primary
key) that can uniquely identify all records in the table. The field Salutation (non-
prime attribute), however, depends on the Student Field rather than the candidate
key. Hence, the table is not in 3NF. To convert it into the 3rd Normal Form, we will
once again partition the tables into two while specifying a new Foreign
Key constraint to identify the salutations for individual records in the Students
table. The Primary Key constraint for the same will be set on the Salutations table
to identify each record uniquely.
Salutation_ID Salutation
1 Ms.
2 Mr.
3 Mrs.
For the above relation to exist in 3NF, all possible candidate keys in the above
relation should be {P, RS, QR, T}.
A relation is in Boyce-Codd Normal Form if satisfies the conditions for third normal
form and for every functional dependency, Left-Hand-Side is super key. In other
words, a relation in BCNF has non-trivial functional dependencies in form X –> Y,
such that X is always a super key. For example - In the above example, Student_ID
serves as the sole unique identifier for the Students Table and Salutation_ID for the
Salutations Table, thus these tables exist in BCNF. The same cannot be said for the
Books Table and there can be several books with common Book Names and the
same Student_ID.
TRUNCATE command is used to delete all the rows from the table and free the
space containing the table.
DROP command is used to remove an object from the database. If you drop a table,
all the rows in the table are deleted and the table structure is removed from the
database.
Write a SQL query to remove first 1000 records from table 'Temporary' based on
'id'.
Write a SQL statement to delete the table 'Temporary' while keeping its relations
intact.
If a table is dropped, all things associated with the tables are dropped as well. This
includes - the relationships defined on the table with other tables, the integrity
checks and constraints, access privileges and other grants that the table has. To
create and use the table again in its original form, all these relations, checks,
constraints, privileges and relationships need to be redefined. However, if a table is
truncated, none of the above problems exist and the table retains its original
structure.
40. What is the difference between DELETE and TRUNCATE statements?
The TRUNCATE command is used to delete all the rows from the table and free the
space containing the table.
The DELETE command deletes only the rows from the table based on the condition
given in the where clause or deletes all the rows from the table if no condition is
specified. But it does not free the space containing the table.
Note: All aggregate functions described above ignore NULL values except for the
COUNT function.
A scalar function returns a single value based on the input value. Following are the
widely used SQL scalar functions:
PostgreSQL was first called Postgres and was developed by a team led by Computer
Science Professor Michael Stonebraker in 1986. It was developed to help
developers build enterprise-level applications by upholding data integrity by making
systems fault-tolerant. PostgreSQL is therefore an enterprise-level, flexible, robust,
open-source, and object-relational DBMS that supports flexible workloads along
with handling concurrent users. It has been consistently supported by the global
developer community. Due to its fault-tolerant nature, PostgreSQL has gained
widespread popularity among developers.
TRUNCATE TABLE name_of_table statement removes the data efficiently and quickly
from the table.
The truncate statement can also be used to reset values of the identity columns
along with data cleanup as shown below:
We can also use the statement for removing data from multiple tables all at once by
mentioning the table names separated by comma as shown below:
TRUNCATE TABLE
table_1,
table_2,
table_3;
4. Define tokens in PostgreSQL?
Partitioned tables are logical structures that are used for dividing large tables into
smaller structures that are called partitions. This approach is used for effectively
increasing the query performance while dealing with large database tables. To
create a partition, a key called partition key which is usually a table column or an
expression, and a partitioning method needs to be defined. There are three types of
inbuilt partitioning methods provided by Postgres:
The type of partition key and the type of method used for partitioning determines
how positive the performance and the level of manageability of the partitioned
table are.
Starting PostgreSQL: ok
The first step of using PostgreSQL is to create a database. This is done by using the
createdb command as shown below: createdb db_name
After running the above command, if the database creation was successful, then the
below message is shown:
CREATE DATABASE
8. How will you change the datatype of a column?
This can be done by using the ALTER TABLE statement as shown below:
Syntax:
Indexes are the inbuilt functions in PostgreSQL which are used by the queries to
perform search more efficiently on a table in the database. Consider that you have a
table with thousands of records and you have the below query that only a few
records can satisfy the condition, then it will take a lot of time to search and return
those rows that abide by this condition as the engine has to perform the search
operation on every single to check this condition. This is undoubtedly inefficient for
a system dealing with huge data. Now if this system had an index on the column
where we are applying search, it can use an efficient method for identifying
matching rows by walking through only a few levels. This is called indexing.
To get the next number 101 from the sequence, we use the nextval() method as
shown below:
SELECT nextval('serial_num');
We can also use this sequence while inserting new records using the INSERT
command:
They are character sequences bound within single quotes. These are using during
data insertion or updation to characters in the database.
There are special string constants that are quoted in dollars.
Syntax: $tag$<string_constant>$tag$ The tag in the constant is optional and when we
are not specifying the tag, the constant is called a double-dollar string literal.
This can be done by using the command \l -> backslash followed by the lower-case
letter L.
13. How can you delete a database in PostgreSQL?
This can be done by using the DROP DATABASE command as shown in the syntax
below:
If the database has been deleted successfully, then the following message would be
shown:
DROP DATABASE
14. What are ACID properties? Is PostgreSQL compliant with ACID?
ACID stands for Atomicity, Consistency, Isolation, Durability. They are database
transaction properties which are used for guaranteeing data validity in case of
errors and failures.
The command enable-debug is used for enabling the compilation of all libraries and
applications. When this is enabled, the system processes get hindered and generally
also increases the size of the binary file. Hence, it is not recommended to switch
this on in the production environment. This is most commonly used by developers
to debug the bugs in their scripts and help them spot the issues. For more
information regarding how to debug, you can refer here.
18. How do you check the rows affected as part of previous transactions?
SQL standards state that the following three phenomena should be prevented
whilst concurrent transactions. SQL standards define 4 levels of transaction
isolations to deal with these phenomena.
To tackle these, there are 4 standard isolation levels defined by SQL standards.
They are as follows:
• Read Uncommitted – The lowest level of the isolations. Here, the transactions are
not isolated and can read data that are not committed by other transactions
resulting in dirty reads.
• Read Committed – This level ensures that the data read is committed at any instant
of read time. Hence, dirty reads are avoided here. This level makes use of read/write
lock on the current rows which prevents read/write/update/delete of that row
when the current transaction is being operated on.
• Repeatable Read – The most restrictive level of isolation. This holds read and write
locks for all rows it operates on. Due to this, non-repeatable reads are avoided as
other transactions cannot read, write, update or delete the rows.
• Serializable – The highest of all isolation levels. This guarantees that the execution
is serializable where execution of any concurrent operations are guaranteed to be
appeared as executing serially.
The following table clearly explains which type of unwanted reads the levels avoid:
Isolation levels Dirty Reads Phantom Reads Non-repeatable reads
19. What can you tell about WAL (Write Ahead Logging)?
Write Ahead Logging is a feature that increases the database reliability by logging
changes before any changes are done to the database. This ensures that we have
enough information when a database crash occurs by helping to pinpoint to what
point the work has been complete and gives a starting point from the point where it
was discontinued.
20. What is the main disadvantage of deleting data from an existing table using the
DROP TABLE command?
DROP TABLE command deletes complete data from the table along with removing the
complete table structure too. In case our requirement entails just remove the data,
then we would need to recreate the table to store data in it. In such cases, it is
advised to use the TRUNCATE command.
'interviewbit' ~* '.*INTervIewBit.*'
22. How will you take backup of the database in PostgreSQL?
We can achieve this by using the pg_dump tool for dumping all object contents in
the database into a single file. The steps are as follows:
Step 2: Execute pg_dump program to take the dump of data to a .tar folder as
shown below:
The commit action ensures that the data consistency of the transaction is
maintained and it ends the current transaction in the section. Commit adds a new
record in the log that describes the COMMIT to the memory. Whereas, a
checkpoint is used for writing all changes that were committed to disk up to SCN
which would be kept in datafile headers and control files.
Conclusion:
SQL is a language for the database. It has a vast scope and robust capability of
creating and manipulating a variety of database objects using commands like
CREATE, ALTER, DROP, etc, and also in loading the database objects using
commands like INSERT. It also provides options for Data Manipulation using
commands like DELETE, TRUNCATE and also does effective retrieval of data using
cursor commands like FETCH, SELECT, etc. There are many such commands which
provide a large amount of control to the programmer to interact with the database
in an efficient way without wasting many resources. The popularity of SQL has
grown so much that almost every programmer relies on this to implement their
application's storage functionalities thereby making it an exciting language to learn.
Learning this provides the developer a benefit of understanding the data structures
used for storing the organization's data and giving an additional level of control and
in-depth understanding of the application.
------------------------------------------------------------
BASIC SQL QUESTIONS
------------------------------------------------------------
1. What is SQL?
SQL (Structured Query Language) is used to communicate with databases for
storing, retrieving, and manipulating data.
------------------------------------------------------------
NORMALIZATION
------------------------------------------------------------
1. What is normalization?
The process of organizing data to minimize redundancy.
------------------------------------------------------------
JOINS
------------------------------------------------------------
Types of Joins:
- INNER JOIN: Matches records in both tables.
- LEFT JOIN: All records from left + matched from right.
- RIGHT JOIN: All records from right + matched from left.
- FULL OUTER JOIN: All records from both with NULLs where no match.
- SELF JOIN: Join a table to itself.
- CROSS JOIN: Cartesian product.
Example:
SELECT e.Name, d.DeptName
FROM Employees e
INNER JOIN Departments d ON e.DeptId = d.DeptId;
------------------------------------------------------------
ADVANCED QUERIES
------------------------------------------------------------
1. Second highest salary:
SELECT MAX(Salary) FROM Employees
WHERE Salary < (SELECT MAX(Salary) FROM Employees);
5. Correlated subquery:
SELECT Name FROM Employees e
WHERE Salary > (SELECT AVG(Salary) FROM Employees WHERE DeptId =
e.DeptId);
------------------------------------------------------------
FUNCTIONS
------------------------------------------------------------
Aggregate: SUM(), AVG(), COUNT(), MAX(), MIN()
Scalar: LEN(), UPPER(), LOWER(), GETDATE(), SUBSTRING()
------------------------------------------------------------
GROUP BY & HAVING
------------------------------------------------------------
GROUP BY: Groups rows with same values.
HAVING: Filters groups after aggregation.
------------------------------------------------------------
INDEXING
------------------------------------------------------------
1. Index speeds up search.
2. Clustered Index: Sorts data physically.
3. Non-Clustered: Creates a separate structure.
4. Only 1 Clustered Index per table.
------------------------------------------------------------
VIEWS
------------------------------------------------------------
1. Virtual table.
2. Can be updated if based on one table.
3. Cannot store data.
Example:
CREATE VIEW HighSalary AS
SELECT * FROM Employees WHERE Salary > 50000;
------------------------------------------------------------
TRIGGERS
------------------------------------------------------------
1. Executes automatically on events.
2. Types: AFTER, INSTEAD OF
Example:
CREATE TRIGGER trg_AfterInsert
ON Employees AFTER INSERT AS
BEGIN
INSERT INTO AuditLog(EmpId, Action)
SELECT ID, 'INSERTED' FROM inserted;
END;
------------------------------------------------------------
STORED PROCEDURE
------------------------------------------------------------
1. Precompiled SQL block.
Example:
CREATE PROCEDURE GetEmpByDept @DeptId INT
AS
BEGIN
SELECT * FROM Employees WHERE DeptId = @DeptId;
END;
------------------------------------------------------------
TRANSACTIONS & ACID
------------------------------------------------------------
1. Atomicity, Consistency, Isolation, Durability.
2. COMMIT: Save changes.
3. ROLLBACK: Undo changes.
4. SAVEPOINT: Intermediate point.
------------------------------------------------------------
TEMP TABLES vs TABLE VARIABLES
------------------------------------------------------------
1. Temp Tables: Stored in tempdb, can be indexed.
2. Table Variables: Stored in memory, limited scope.
------------------------------------------------------------
REAL-WORLD QUERY SCENARIOS
------------------------------------------------------------
1. Nth highest salary:
SELECT Salary FROM (
SELECT DISTINCT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS rnk
FROM Employees
) AS T WHERE rnk = N;
I completed my schooling at Pristine Children's High School in Muzaffarpur, where I built a strong
Soon after graduation, I joined HCL Technologies as a fresher and have been working there ever
since. At HCL, I have been part of a development team working on a Sales HR Track Application
- Implementing best practices in code security, performance optimization, and API integration
Apart from development, I have also gained hands-on exposure in resolving production issues,
I am really excited about this opportunity with Infosys, as I believe it will allow me to take on more
I am really grateful for the opportunities and learning I have had at HCL Technologies, especially as
a fresher. It gave me a strong foundation in .NET Core and real-time project experience in a
structured environment.
However, I believe it is the right time for me to explore new challenges and work on more diverse
and large-scale projects that Infosys is known for. I am particularly impressed by Infosys' focus on
Joining Infosys would provide me the platform to expand my technical skillset, learn from industry
leaders, and contribute to high-impact projects while growing both professionally and personally.
In my project, we faced an issue where some of our APIs were taking too long to respond due to
inefficient database queries. I worked with the team to identify slow queries, added proper indexing,
and optimized the stored procedures. This significantly reduced the response time and improved
performance.
My biggest strength is problem-solving and staying calm under pressure. I analyze issues
One area I am working on is public speaking. While I communicate well within teams, I have started
In 5 years, I see myself as a senior software engineer or technical lead, contributing to end-to-end
Note: This project was built using .NET Core for backend and React.js for frontend. API calls were made
using Fetch API in React. LINQ was not used; instead, ADO.NET and stored procedures were utilized for
data access.
The system was designed to track sales performance and HR-related activities of employees. It included
modules like attendance, payroll tracking, leave management, and performance monitoring.
I mainly worked on backend modules like attendance tracking, leave workflows, role-based access, and sales
It followed a layered architecture using .NET Core Web API for backend, React for frontend, and SQL Server
as database. We followed best practices with repository-service-controller separation and SOLID principles.
I focused on backend development, building REST APIs, implementing business logic, and managing
I used ASP.NET Core Web API controllers with routing and proper data validation annotations to handle
CRUD operations.
JWT (JSON Web Tokens) were used for authentication and role-based authorization was implemented using
JWT is a token-based stateless authentication mechanism. After login, a token is generated and sent with
each request for authorization.
APIs were protected using HTTPS, JWT authentication, and input validation. CORS policies were configured
I used ADO.NET and stored procedures for DB access, focusing on performance and secure data
transactions.
Yes, I used stored procedures for all database operations to improve performance and control business logic
I used SQL transactions with stored procedures and managed connection and command execution within
By using asynchronous operations, optimizing stored procedures, and caching static data where necessary.
Yes, I used async methods in .NET Core for all I/O-bound operations to improve scalability.
Salary and other sensitive data were secured using HTTPS and access restrictions based on user roles.
SQL Injection was prevented through parameterized commands in ADO.NET and stored procedures. XSS
It was deployed using IIS with automated build and release pipelines through Azure DevOps.
React used Fetch API to call .NET Core APIs. I ensured endpoints returned standardized responses and
Only minor adjustments during integration testing. My main role was focused on .NET Core development.