KEMBAR78
Interview Notes Merged | PDF | Model–View–Controller | World Wide Web
0% found this document useful (0 votes)
54 views315 pages

Interview Notes Merged

Uploaded by

kumar mrinal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views315 pages

Interview Notes Merged

Uploaded by

kumar mrinal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 315

ASP.

NET Web Forms:

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:

ASP.NET MVC (Model-View-Controller) is a framework that was introduced by Microsoft in 2009 as


part of the .NET Framework 3.5. It provides an alternative to Web Forms, offering a framework that
emphasizes a clear separation of concerns and full control over the generated HTML markup. It
follows the Model-View-Controller (MVC) architectural pattern, which allows developers to build
scalable, testable, and maintainable web applications.

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:

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:

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:

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:

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.

• Blazor WebAssembly: Runs in the browser using WebAssembly (WASM), allowing


developers to write rich, client-side web applications in C#.

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.

Comparison and Migration Path

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.

• Blazor vs. JavaScript Frameworks: Blazor offers an alternative to traditional JavaScript


frameworks (like React or Angular) by enabling developers to use C# for client-side
development. This provides a more unified codebase for full-stack development.

Choosing the Right Framework

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.

What are Traditional Web Applications (Server-Side Rendered)?

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.

What is Interactive Client-Side Applications (Single Page Applications – SPAs)?

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.

Introduction to ASP.NET Core Framework

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.

History of ASP.NET Core

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 a Cross-Platform, Open-Source, High-Performance framework used for building


modern, cloud-based, and internet-connected applications that run on Windows, Linux, macOS, and
Docker. According to Microsoft:

• 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

Why ASP.NET 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:

• Download and inspect the source code.


• Modify and customize it as needed.

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

Lightweight and Modular:

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.

Built-in Dependency Injection:

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.

ASP.NET Core Support Policy and Release Lifecycle:

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.

For a better understanding, please have a look at the following image:

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

What the ASP.NET Core Doesn’t Have?

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.

• Web.config File: Configuration is now handled


using appsettings.json, appsettings.{Environment}.json, environment variables, and other
configuration providers.

• HTTP Handlers and HTTP Modules: Replaced by Middleware Components in the ASP.NET
Core request pipeline.

Differences Between .NET Framework vs .NET Core Framework

The following are the Differences Between .NET Framework and .NET Core

.NET Framework

• Platform: Designed exclusively for Windows.

• Architecture: Monolithic, including all features by default, leading to larger applications.


• Performance: Does not match the performance optimizations of .NET Core due to its older
architecture.

• Support and Development: In maintenance mode with Microsoft primarily releasing


security updates and critical fixes; no new features are being added.

• Open Source: It is not open source.

• 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

• Platform: Cross-platform, running on Windows, Linux, and macOS.

• Architecture: Modular, allowing developers to include only necessary packages via NuGet,
resulting in lighter and more efficient applications.

• Performance: Optimized for high performance and scalability.

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

.NET Core (.NET) vs ASP.NET Core:

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:

.NET Core (.NET):


• .NET Core (.NET) is the cross-platform software. It provides the Runtime Environment where
the ASP.NET Core Web Applications will run.

• Install .NET Core Runtime to run applications and install .NET Core SDK to build applications.

• .NET 8 is the latest stable version.

ASP.NET Core:

• ASP.NET Core is an Open-Source, Cross-Platform Framework using which we can develop


different types of Web Applications, such as MVC, Web API, Razor Pages, etc.

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

• ASP.NET Core 8 is the latest stable version.

Note: ASP.NET Core does not have a separate versioning system; it is the same as the other .NET
Core versions.

Difference Between .NET Core and .NET Framework

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.

Here are some of the key differences as of my last update:

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 Framework: Not 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.

Modularity and Lightweight:

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

Performance and Scalability:

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

Support for Microservices:

• .NET Framework: .Net Framework does not support to develop Microservices.

• .NET Core: Net Core support to develop Microservices.

CLR and Execution:

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

Windows API Access:

• .NET Framework: Provides easy access to Windows-specific APIs and features.

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

Tooling and Language Support:

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

Ecosystem and Libraries:

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

Versioning and Compatibility:

• .NET Framework: Multiple versions coexist on a system, potentially leading to versioning


challenges and conflicts.

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

Which Is Better Between .NET Core and .NET Framework?

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:

1. Platform Compatibility: If you need cross-platform compatibility and want to develop


applications that can run on Windows, macOS, and Linux, .NET Core (or its newer versions
like .NET 5, .NET 6, etc.) is the better choice.

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.

3. Windows Ecosystem: If your application relies heavily on Windows-specific APIs and


features, and you are targeting primarily Windows environments, then .NET Framework
might be more appropriate.
4. Web Development: For web development, .NET Core (now ASP.NET Core) offers improved
performance, cross-platform capabilities, and modern web frameworks (MVC, Razor Pages,
Web API) that can be advantageous.

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.

Is .NET Core Replacing .Net 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.

Does .NET 5 Replace .NET Framework?

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.

• Performance and Modernization: .NET 5 focuses on improved performance, modularity,


and modern development practices. It carries forward the performance enhancements
introduced in .NET Core.
• Compatibility: While .NET 5 aims to encompass the capabilities of both .NET Core and .NET
Framework, there might be certain scenarios where migration or adjustments are needed to
move from .NET Framework to .NET 5.

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

Is .NET 6 the Same as the .NET Core?

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.

Why Is .NET Core Faster Than .NET Framework?


.NET Core is generally considered to be faster than the traditional .NET Framework due to a
combination of factors related to its design, architecture, and optimizations. Here are some reasons
why .NET Core tends to offer better performance compared to the .NET Framework:

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

• Platform-Dependent Optimizations: .NET Core takes advantage of platform-specific


optimizations, leveraging underlying operating system features to improve performance.

• Cross-Platform Performance Focus: The emphasis on cross-platform compatibility in .NET


Core led to performance optimizations that work consistently across different operating
systems. This focus on performance contributed to overall speed improvements.

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

Why Must You Migrate From .NET Framework to .NET Core?

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:

• Cross-Platform Compatibility: .NET Core is designed for cross-platform development,


allowing you to run your Windows, macOS, and Linux applications. This can expand your
application’s reach and make it accessible to a broader audience.
• Performance Improvements: .NET Core includes performance optimizations, such as an
optimized Just-In-Time (JIT) compiler and memory management improvements, that can
result in faster application startup times and overall better performance.

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

Introduction to ASP.NET Core MVC Framework

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?

2. How Does MVC Design Pattern Work in ASP.NET Core?

3. What is ASP.NET Core MVC?


4. Features of ASP.NET Core 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.

How Does MVC Design Pattern Work in ASP.NET Core?

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.

So, when we request something like https://localhost:7132/Student/Details/2 from a web browser,


the following things happen to handle the request.

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.

Role of Model in MVC Design Pattern:


The Model in an MVC application represents the application’s state and business logic. That means
the Model is the component in the MVC Design pattern used to manage the data, i.e., the
application’s state in memory. The Model represents a set of classes used to describe the
application’s validation, business, and data access logic. So, in our example, the model consists of
Student and StudentBusinessLayer classes.

Student.cs

namespace ASPNETCoreMVCApplication.Models

public class Student

public int StudentID { get; set; }

public string? Name { get; set; }

public string? Gender { get; set; }

public string? Branch { get; set; }

public string? Section { get; set; }

StudentBusinessLayer.cs

namespace ASPNETCoreMVCApplication.Models

public class StudentBusinessLayer

public IEnumerable<Student> GetAll()

//logic to return all employees

return new List<Student>();

public Student GetById(int StudentID)

//logic to return an employee by employeeId

Student student = new Student()

{
StudentID = StudentID,

Name = "James",

Gender = "Male",

Branch = "CSE",

Section = "A2",

};

return student;

public void Insert(Student student)

//logic to insert a student

public void Update(Student student)

//logic to Update a student

public void Delete(int StudentID)

//logic to Delete a 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.

Key Responsibilities of Models:

• Retrieve and store data in the database or other storage mechanisms.

• Provide data to the controller as needed.

• 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>Student ID: </td>

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

Key Responsibilities of Views:

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

Role of Controller in MVC Design Pattern:

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

public class StudentController : Controller

public ActionResult Details(int studentId)

{
StudentBusinessLayer studentBL = new StudentBusinessLayer();

Student studentDetail = studentBL.GetById(studentId);

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

Key Responsibilities of Controllers:

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

What is ASP.NET Core MVC?

ASP.NET Core MVC is a web application development framework developed by Microsoft. It is a


modern implementation of the Model-View-Controller (MVC) architectural pattern designed to build
dynamic web applications and web APIs. It is part of the ASP.NET Core platform, a cross-platform,
high-performance framework for building modern, cloud-based, and internet-connected
applications. So, the point that you need to remember is that MVC is a Design Pattern, and ASP.NET
Core MVC is a Framework based on the MVC Design Pattern.

Features of ASP.NET Core MVC:

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.

• Extensive Built-In Middleware: The framework provides extensive built-in middleware


components that can handle requests for authentication, routing, session state, and more.
Developers can also create custom middleware.

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

ASP.NET Core MVC:

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.

3. If your team members have knowledge of ASP.NET Core MVC.

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.

What is a Controller in ASP.NET Core?

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:

• Inherits from the Controller base class.

• Contains action methods that respond to HTTP requests.

• Interacts with models to retrieve or update data.

• Selects views to render HTML or returns data directly.

How Controllers Work in ASP.NET Core?

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.

How do you add Controllers to the ASP.NET Core Application?

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.

Step 1: Creating ASP.NET Core Empty Web Application

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.

Step 2: Adding Controllers Folder

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.

Step 3: Adding Controller in ASP.NET Core

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:

1. MVC Controller – Empty: It will create an Empty Controller.

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.

Rules for Controller:

1. Naming Convention: Controllers are typically named with the suffix Controller, like
HomeController or ProductController.

2. Inheriting from ControllerBase: Controllers usually inherit from the ControllerBase or


Controller class, which provides many methods and properties for handling requests and
responses.

I hope you now have clarity on ASP.NET Core MVC Controllers. Let’s move forward and understand
the next topic, Action Methods.

What are 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 ;

NAMESPACE FIRSTC ORE MVCWEBAPPLICATION .C ONTROLLERS

PUBLIC CLASS S TUDENT C ONTROLLER : C ONTROLLER

PUBLIC STRING G ETALLS TUDENTS()

RETURN "RETURN ALL S TUDENTS ";

How Do We Call an Action Method of a Controller?

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.

Modifying the Program Class:

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.

NAMESPACE FIRSTC ORE MVCWEBAPPLICATION

PUBLIC CLASS PROGRAM

PUBLIC STATIC VOID M AIN( STRING [] ARGS)

// CREATE A WEBAPPLICATION BUILDER , WHICH PROVIDES VARIOUS CONFIGURATION SETTINGS


// AND SERVICES FOR THE WEB APPLICATION

VAR BUILDER = WEBAPPLICATION .C REATE B UILDER( ARGS);

// ADD MVC SERVICES TO THE SERVICE CONTAINER .

// THIS INCLUDES SUPPORT FOR CONTROLLERS AND VIEWS.

BUILDER.S ERVICES.ADDMVC ();

// BUILD THE APPLICATION USING THE CONFIGURED BUILDER

VAR APP = BUILDER .B UILD();

// ENABLE ROUTING MIDDLEWARE , WHICH MATCHES INCOMING HTTP REQUESTS TO ENDPOINTS DEFINED IN
THE APPLICATION

APP.USE ROUTING ();

// MAP THE DEFAULT CONTROLLER ROUTE (CONVENTION: {CONTROLLER=HOME}/{ACTION=INDEX}/{ID?})

// THIS MEANS IF NO SPECIFIC ROUTE IS PROVIDED , IT WILL DEFAULT TO HOMECONTROLLER AND INDEX
ACTION

APP.MAPC ONTROLLER ROUTE (

NAME : "DEFAULT ", // N AME OF THE ROUTE

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.

PUBLIC STRING G ETS TUDENTS B YN AME( STRING NAME )

RETURN $"RETURN ALL S TUDENTS WITH N AME : { NAME }";

Now run the application, navigate to the


URL http://localhost:<portnumber>/student/GetStudentsByName?name=james, and see the
output as shown in the below image.

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.

When should we create a new controller?

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.

How Many Controllers can we have in a Single Application?

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.

How is Controller Instance Created in ASP.NET Core MVC?

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.

How is Controller Instance Created in ASP.NET Core MVC?

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.

void Release(ControllerContext context, object controller):

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

ValueTask ReleaseAsync(ControllerContext context, object controller):

• This method is responsible for asynchronously releasing a controller instance. It provides a


way to perform any necessary cleanup or disposal of the controller in an asynchronous
manner. The ControllerContext parameter provides contextual information about the
current request and the controller being released. The object parameter is the instance of
the controller that needs to be released.

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

Models in 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.

What is a Model in ASP.NET Core MVC?

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.

Adding Models Folder in ASP.NET Core 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.

NAMESPACE FIRSTC ORE MVCWEBAPPLICATION .MODELS

PUBLIC CLASS S TUDENT

PUBLIC INT S TUDENT I D { GET ; SET; }

PUBLIC STRING ? N AME { GET ; SET; }

PUBLIC STRING ? B RANCH { GET ; SET; }

PUBLIC STRING ? S ECTION { GET; SET; }

PUBLIC STRING ? G ENDER { GET; SET; }


}

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.

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

NAMESPACE FIRSTC ORE MVCWEBAPPLICATION .MODELS

PUBLIC INTERFACE IS TUDENT R EPOSITORY

STUDENT GETSTUDENTBYID(INT STUDENTID);

As you can see, we created the above interface with one method, the GetStudentById() method,
which retrieves the student details by the student ID.

Creating StudentRepository class:

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.

USING S YSTEM .C OLLECTIONS .G ENERIC ;

USING S YSTEM .LINQ ;

NAMESPACE FIRSTC ORE MVCWEBAPPLICATION .MODELS

PUBLIC CLASS S TUDENT REPOSITORY : IS TUDENT REPOSITORY

PUBLIC LIST<S TUDENT > DATA S OURCE ()

RETURN NEW LIST<S TUDENT >()

{
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" }

};

PUBLIC S TUDENT G ETS TUDENT B YI D( INT S TUDENT I D)

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.

USING FIRSTC ORE MVCWEBA PPLICATION .MODELS;

USING MICROSOFT .A SPN ETC ORE .MVC ;

NAMESPACE FIRSTC ORE MVCWEBAPPLICATION .C ONTROLLERS

PUBLIC CLASS S TUDENT C ONTROLLER : C ONTROLLER

PUBLIC JSONRESULT G ETS TUDENT DETAILS( INT I D)

STUDENTREPOSITORY REPOSITORY = NEW STUDENTREPOSITORY();

STUDENT STUDENT DETAILS = REPOSITORY.GETSTUDENTBYID(ID);


RETURN JSON( STUDENT DETAILS);

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.

NAMESPACE FIRSTC ORE MVCWEBAPPLICATION

PUBLIC CLASS PROGRAM

PUBLIC STATIC VOID M AIN( STRING [] ARGS)

// CREATE A WEBAPPLICATION BUILDER , WHICH PROVIDES VARIOUS CONFIGURATION SETTINGS

// AND SERVICES FOR THE WEB APPLICATION

VAR BUILDER = WEBAPPLICATION .C REATE B UILDER( ARGS);

// ADD MVC SERVICES TO THE SERVICE CONTAINER .

// THIS INCLUDES SUPPORT FOR CONTROLLERS AND VIEWS .

BUILDER.S ERVICES.ADDMVC ();

// BUILD THE APPLICATION USING THE CONFIGURED BUILDER

VAR APP = BUILDER .B UILD();

// ENABLE ROUTING MIDDLEWARE , WHICH MATCHES INCOMING HTTP REQUESTS TO ENDPOINTS DEFINED IN
THE APPLICATION

APP.USE ROUTING ();

// MAP THE DEFAULT CONTROLLER ROUTE (CONVENTION: {CONTROLLER=HOME}/{ACTION=INDEX}/{ID?})

// THIS MEANS IF NO SPECIFIC ROUTE IS PROVIDED , IT WILL DEFAULT TO HOMECONTROLLER AND INDEX
ACTION

APP.MAPC ONTROLLER ROUTE (

NAME : "DEFAULT ", // N AME OF THE ROUTE

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

Now run the application and navigate to https://localhost:<Port


Numbet>/Student/GetStudentDetails/102 URL, and you will see the student data in JSON format,
as expected in the browser, as shown in the image below.

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.

Use Cases of Models in MVC Design Pattern:

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

• Communication: Models facilitate communication between different parts of the


application, such as controllers, views, and data access layers.

Views in ASP.NET Core MVC Application

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.

1. What are Views in ASP.NET Core MVC Application?

2. Where are View Files Stored in ASP.NET Core MVC Application?

3. How to create View in ASP.NET Core?

4. How do we return views from action methods?

5. What is the difference between View() and View(object model) Extension Methods?

6. How do you specify the Absolute view file path?


7. How Does the Controller Action Method Identify the View in ASP.NET Core MVC?

What is a View in ASP.NET Core MVC Application?

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.

Types of Views in ASP.NET Core MVC:

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

Where are Views Placed in ASP.NET Core MVC Application?

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.

Example to Understand Views in ASP.NET Core MVC Application:

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.

Adding Home Controller

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

USING MICROSOFT .A SPN ETC ORE .MVC ;

NAMESPACE FIRSTC ORE MVCWEBAPPLICATION .C ONTROLLERS

PUBLIC CLASS HOME C ONTROLLER : C ONTROLLER

PUBLIC VIEWRESULT I NDEX()

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.

Creating Index View

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>

<META NAME="VIEWPORT" CONTENT="WIDTH=DEVICE -WIDTH" />

<TITLE>INDEX</TITLE>

</HEAD>

<BODY>

<H1>INDEX VIEW BELONGS TO VIEWS/HOME FOLDER</H1>

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

Understanding View() Method in ASP.NET Core MVC Application:

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.

View() vs View(object model) Extension Methods:

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>

<META NAME="VIEWPORT" CONTENT="WIDTH=DEVICE -WIDTH" />

<TITLE>TEST</TITLE>

</HEAD>

<BODY>

<H1>TEST VIEW COMING FROM VIEWS/HOME FOLDER</H1>

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

USING MICROSOFT .A SPN ETC ORE .MVC ;

NAMESPACE FIRSTC ORE MVCWEBAPPLICATION .C ONTROLLERS

PUBLIC CLASS HOME C ONTROLLER : C ONTROLLER


{

PUBLIC VIEWRESULT I NDEX()

RETURN VIEW("T EST");

Run the application and navigate to the “/Home/Index” URL. As shown in the image below, the
response comes from the test view.

How do you specify the Absolute View File Path?

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.

USING MICROSOFT .A SPN ETC ORE .MVC ;

NAMESPACE FIRSTC ORE MVCWEBAPPLICATION .C ONTROLLERS

PUBLIC CLASS HOME C ONTROLLER : C ONTROLLER

PUBLIC VIEWRESULT I NDEX()

RETURN VIEW("VIEWS/HOME /TEST. CSHTML ");

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.

• Example: return View(“~/Views/Home/Index.cshtml”);

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.

Another way of Creating Views:

Let us add a new action to the HomeController with the name About. So, please modify the
HomeController as shown below.

USING MICROSOFT .A SPN ETC ORE .MVC ;

NAMESPACE FIRSTC ORE MVCWEBAPPLICATION .C ONTROLLERS

PUBLIC CLASS HOME C ONTROLLER : C ONTROLLER

PUBLIC VIEWRESULT I NDEX()

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.

Understanding the ASP.NET Core MVC Project File and Folder


Structure:
Several key components work together in an ASP.NET Core MVC application to ensure
the application runs smoothly. Let’s discuss the roles and responsibilities of each folder
and file of the ASP.NET Core MVC application:
Connected Services
This section within the Solution Explorer in Visual Studio allows us to easily connect to
external services such as Azure, Office 365, REST APIs, or third-party services. It helps
integrate and configure APIs, SDKs, or services that your application depends on. It
simplifies consuming external services by managing the necessary configurations and
client code generation.
Dependencies Folder
The Dependencies folder contains the NuGet packages and other dependencies your
project relies on. It includes:
• Packages: The NuGet packages that your project uses.
• SDKs: The .NET SDKs your project is targeting.
• Projects: Other projects within the same solution that your project
references.
Properties Folder
This folder contains the launchSettings.json file, which is used to configure how the
application is launched, including profiles for IIS Express and other environments. It
includes settings for environment variables, application URL, and other settings related to
how the application is run during development. You can specify different settings for
different environments (like Development, Staging, and Production) in this file.
wwwroot Folder
The wwwroot folder is the root folder for all static content your application uses, such as
CSS, JavaScript, and image files. Files in this folder are accessible via a URL without
additional configuration, making it ideal for storing assets directly needed in client-side
interactions.
Controllers Folder
The Controllers folder contains the controller classes. Controllers handle incoming HTTP
requests, process them (often using services and models), and return the appropriate
responses (usually views or JSON data) to the client. The methods inside controller
classes are called actions and mapped to different routes defined in the application.
Models Folder
The Models folder contains classes that represent the data of the application and logic to
manage the data, i.e., how the data is going to be handled. Models represent the shape
of the data and its business logic. This includes validation rules, business logic, and data-
access logic. These classes are also used to pass data between the controllers and views.
They often correspond to database tables in applications that use Entity Framework Core.
For example, a Product model might represent a Product table in a database.
Views Folder
The Views folder contains files to generate the HTML content returned to the client. It
typically includes subfolders for each controller, containing the views associated with each
action. These files are typically Razor view files (.cshtml), which mix HTML markup with
C# code for dynamic content generation.
Shared Folder
The Shared folder contains views and partial views that are shared across multiple other
views, such as layout templates (e.g., _Layout.cshtml), error pages, or partial views used
across various pages of the application. The Shared folder is typically located under the
Views directory.
_ViewStart.cshtml File
The _ViewStart.cshtml file is a special file in the Views folder that runs before every view
in the application is executed. It is used to define common settings for all views, like
specifying a common layout file (_Layout.cshtml) for the views. This makes it ideal for
setting layout pages and other common settings.
_ViewImports.cshtml File
The _ViewImports.cshtml file allows us to add common namespaces and Razor directives
that we want to be available in all our views, such as @using declarations for namespaces,
@inject for dependency injection, and @model declarations, to be available to all views
without having to add them in each view individually. It helps to avoid repeating the same
imports across multiple views.
appsettings.json File
The appsettings.json file stores application configuration settings. It is a JSON file that
includes settings such as connection strings, framework configuration settings, logging,
and custom application settings. These settings can be loaded into the application at
runtime and vary by environment.
Program.cs File
The Program.cs file is the application’s entry point. It sets up the web host that will host
the app, configures services, logging, configuration sources, and the HTTP server, and
configures the ASP.NET Core application pipeline and services.
ASP.NET Core MVC Setup:
The ASP.NET Core Web APP (Model-View-Controller) Project template includes the
required MVC setup by default. To confirm this, open the Program.cs class file and the
framework has added the required MVC Services and MVC Request processing pipeline,
as shown in the image below.
namespace SampleMVCWeb

public class Program

public static void Main(string[] args)

var builder = WebApplication.CreateBuilder(args);

// Add MVC Services to the container.

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.

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

//MVC Request Processing Pipeline

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.

What is Routing in ASP.NET Core MVC?


Routing in ASP.NET Core MVC is a mechanism that inspects the incoming HTTP request
(i.e., URLs) and then maps those HTTP requests to the appropriate controller actions. It
enables the framework to determine what code to execute based on the URL of the
request. Routing is an important component of ASP.NET Core MVC applications,
providing the ability to define URL patterns and manage how URLs are processed and
handled by the application.
How Does Routing Work in ASP.NET Core?
In simple words, Routing is a pattern-matching system that monitors an incoming HTTP
request and decides what to do with that incoming HTTP request. When the client makes
a request, i.e., an HTTP Request, the routing engine first receives it. Once the routing
engine receives an HTTP request, the routing engine tries to find the route pattern that
matches the requested URL with already registered routes. Routes contain information
about the Controller name, action method name, method type (Get, Post, Put, Patch,
Delete), method parameters, route data, etc.
If it finds a matching URL pattern for the incoming request, it forwards the request to the
appropriate controller and action method. If there is no match for the incoming HTTP
request URL Pattern, it returns a 404 HTTP status code to the client. For a better
understanding, please have a look at the following diagram.

What are the Different Types of Routing Supported by ASP.NET Core


MVC?
We can configure routes in the ASP.NET Core MVC Web Application in two ways. They
are as follows:
1. Convention-Based Routing
2. Attribute-Based Routing.
What is Conventional Based Routing in ASP.NET Core MVC Web
Application?
Conventional-based routing in ASP.NET Core MVC defines URL patterns and maps them
to controller actions based on conventions rather than explicitly specifying routes on each
action or controller. Conventional-based routing follows a set of conventions to map
incoming requests to specific controller actions. It is configured globally in the Program.cs
file using the MapControllerRoute middleware. This method allows for centralized route
configuration, making it easy to manage and understand how URLs map to controllers
and actions.
What is Attribute-Based Routing in ASP.NET Core MVC Application?
Attribute-based routing in ASP.NET Core MVC allows developers to define routing directly
on controller actions or at the controller level using attributes (decorators). This approach
provides more control and flexibility over how URLs are mapped to actions compared to
conventional routing, where routes are configured globally in the Program.cs file. This
approach is useful for APIs and scenarios where URLs need to be explicitly defined and
customized.
In this article, we will discuss Conventional Based Routing in Details, and in our
upcoming articles, we will discuss Attribute-Based Routing in ASP.NET Core MVC
Applications.
Understanding Routing in ASP.NET Core MVC Application:
First, create an ASP.NET Core Application using the ASP.NET Core Model-View-
Controller Template. To create an ASP.NET Core Web Application with the Model-View-
Controller 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 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

public class HomeController : Controller

public ViewResult Index()

return View();

public ViewResult Details(int id)


{

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

public class Program

public static void Main(string[] args)

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.

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.

Understanding How Routing Works in ASP.NET Core MVC Application:


Registration of Route Templates (MapControllerRoute):
The MapControllerRoute method is invoked during the application startup process to
define the route templates and their corresponding patterns. It registers all the route
templates into the route table once when the application starts. MapControllerRoute does
not execute for each incoming request. Instead, it only runs during the application startup
to populate the route table with the defined route templates.
MapControllerRoute implicitly sets up the endpoint middleware (i.e., UseEndpoints)
necessary for handling the routes. The UseEndpoints middleware is responsible for
executing the corresponding endpoints when a matching request comes in. So,
MapControllerRoute sets up the routes once at startup and registers the UseEndpoints
middleware, which executes the corresponding endpoint for each request that matches a
route.
Routing Middleware (UseRouting):
The UseRouting middleware examines incoming HTTP requests and matches them
against the route template stored in the route table to determine the appropriate routes. It
runs for each incoming HTTP request.
When a request arrives, the UseRouting middleware parses the URL and matches it
against the defined route templates stored in the route table. If a match is found, it then
extracts values (like controller name, action method name, and parameters) and stores
them in the HttpContext under RouteData. If no match is found, it will return a 404 error to
the client.
Determining the Controller and Action (UseEndpoints):
After UseRouting identifies a matching route and prepares the necessary context (like
controller, action, and parameters), control is passed to the UseEndpoints middleware.
This is where the actual decision to execute a specific controller action is made.
UseEndpoints evaluates the route data provided by UseRouting and invokes the
appropriate controller and action method.
Who Decides Which Action Method Executes:
The decision of which action method of which controller to execute is primarily made by
the UseEndpoints middleware, which uses the route data populated by UseRouting.
Based on the matched route and the parameters provided in the URL, UseEndpoints
routes the request to the specific controller action that matches the criteria defined in the
route table.
Understanding the Default Route in ASP.NET Core MVC:
The default route is created with the following URL Pattern. So, if we don’t specify anything
in the URL, then by default, the Index action method of the Home Controller class will
handle the request.
{controller=Home}/{action=Index}/{id?}
In this example, the MapControllerRoute method defines a default route. The pattern
parameter specifies the route template, where {controller}, {action}, and {id} are
placeholders for route parameters. The name parameter gives the route a name, which
can be used for generating URLs. The meaning of the placeholders are as follows:
• {controller}: Represents the name of the controller class.
• {action}: Represents the action method name within the controller.
• {id?}: Represents an optional route parameter called “id”.
With this configuration, an incoming URL like /Home/Index would match the Index action
method of the HomeController. Similarly, /Products/Details/5 would match the Details
action method of the ProductsController with an id parameter set to 5.
Understanding Route Template in ASP.NET Core MVC Application:
The default route is created with the URL
Pattern: {controller=Home}/{action=Index}/{id?}
As you can see in the default route template {controller=Home}/{action=Index}/{id?},
we have a question mark at the end of the id parameter, which makes the id parameter
optional. That means the following two requests now map to the same Details action
method of the Home Controller class.
/Home/Details/1
/Home/Details
In the default route template {controller=Home}/{action=Index}/{id?}, the
value Home in {controller=Home} is the default value for the Controller. Similarly, the
value Index in {action=Index} is the default value for the action method. That means if
we navigate to the application’s root URL, as shown below, then that request will be
handled by default by the Index action method of the Home Controller class.
http://localhost:52190/
The following two URLs are also mapped to the Index action method of the
HomeController class.
http://localhost:52190/Home
http://localhost:52190/Home/Index
The default route works fine for most of the ASP.NET Core MVC Web Applications. For
example, create a Controller named StudentController and copy and paste the following
code into it.
using Microsoft.AspNetCore.Mvc;

namespace RoutingInASPDotNetCoreMVC.Controllers

public class StudentController : Controller

public string Index()

return "Index() Action Method of StudentController";

public string Details(int? id)

return $"Details({id}) Action Method of StudentController";

}
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

public class Program

public static void Main(string[] args)

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.

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

defaults: new { controller = "Student", action = "Index" }

);

//https://localhost:44359/StudentDetails/10

app.MapControllerRoute(

name: "StudentIndex",

pattern: "StudentDetails/{ID}",

defaults: new { controller = "Student", action = "Details" }

);

//For Rest of the Controller Actions including the Default Home Controller Index

app.MapControllerRoute(

name: "default",

pattern: "{controller}/{action}/{id:int?}",

defaults: new { controller = "Home", action = "Index" }

);

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.

Attribute Routing vs Conventional Routing in ASP.NET Core


In ASP.NET Core, Routing determines how an HTTP request matches a controller action.
There are two primary approaches to routing in ASP.NET Core: Attribute Routing and
Conventional Routing. Each approach has its unique characteristics, advantages, and use
cases.
Conventional Routing in ASP.NET Core
Conventional routing uses a predefined pattern to map requests to controller actions. It
involves defining routes in the Program.cs file. This approach relies on a predefined
pattern to match the URL paths to the corresponding controller actions. It typically
specifies placeholders for the controller name, action name, and optional parameters. This
approach is useful for applications with a clear and consistent URL structure across the
entire application.
Advertisements
Characteristics of Conventional Routing:
• Routes are defined globally in a centralized location, typically in the
Program.cs file.
• It implicitly uses route templates associated with controllers and actions
through naming conventions.
• Parameters can be specified within the route templates to capture values
from the URL.
Advantages of Conventional Routing:
• Simplifies route management by centralizing route definitions, making it
easier to understand and manage the application’s URL structure.
• Ideal for large applications with a hierarchical URL structure that follows a
consistent pattern.
Disadvantages of Conventional Routing:
• Less flexible in defining granular or action-specific routes directly on
controllers or actions.
• This can lead to more complex route management in highly dynamic URL
pattern applications.
When to use Conventional Routing?
• Large Applications with Standardized URL Patterns: Conventional
routing is ideal for large applications with many controllers and actions but
standardized URL patterns. It reduces the need to decorate each action
method with route attributes, keeping the code cleaner.
• Centralized Route Configuration: Conventional routing provides this
advantage if you prefer to have routes defined and managed in a centralized
location. It allows for easier changes to route patterns without modifying
individual controllers or actions.
• Simple CRUD Operations: For applications that follow a straightforward
CRUD (Create, Read, Update, Delete) pattern, conventional routing can be
more straightforward and less verbose than attribute routing.
Attribute Routing in ASP.NET Core
Attribute routing, introduced in later versions of ASP.NET, allows for more granular control
over the URLs by defining routes directly on actions and controllers using attributes. This
approach offers greater flexibility in defining routes, including specifying complex route
patterns and constraints directly on the action methods or controllers.
Characteristics of Attribute Routing:
• Routes are defined using attributes on controllers and actions, allowing for
detailed and customized route definitions.
• It offers greater flexibility in defining routes that do not follow a
conventional pattern.
• Supports the definition of complex route templates, including using
multiple parameters, constraints, and even dynamically generating URLs.
Advantages of Attribute Routing:
• Provides greater control and precision over routing, allowing for complex
and custom route patterns that are not easily achieved with conventional
routing.
• Facilitates the organization of routing logic by keeping it closer to the
action methods it applies to, improving readability and maintainability.
Disadvantages of Attribute Routing:
• This can lead to a scattered routing configuration if not managed carefully,
as routes are defined across different controllers and actions.
• It requires more effort to understand the routing configuration as it is not
centralized.
When to use Attribute Routing:
• Fine-grained URL Control: When you need precise control over your
application’s URL patterns, attribute routing is the way to go. It’s particularly
useful for designing RESTful APIs where URLs represent resources and
operations on those resources.
• Complex Route Patterns: Attribute routing shines when dealing with
complex routes that conventional routing struggles with, such as routes that
need to capture multiple parameters or have custom constraints.
• Versioning APIs: For applications that involve API versioning, attribute
routing makes it easier to define different routes for different API versions
within the same application.
• Mixing Static and Dynamic Segments: If you need to mix static URL
segments with dynamic ones in a single route, attribute routing provides the
flexibility to accomplish this easily.
The choice between attribute routing and conventional routing depends on your
application’s specific needs. Conventional routing is often more suitable for applications
that benefit from centralized route definitions and have a uniform URL structure. On the
other hand, attribute routing is preferred for applications requiring detailed control over
route configurations, such as APIs or applications with complex routing requirements. It’s
also worth noting that ASP.NET Core supports combining both routing methods in the
same application, allowing developers to choose the most appropriate routing strategy for
each controller or action.

What are Filters in ASP.NET Core MVC?


Filters are used to add cross-cutting concerns, such as Logging, Authentication,
Authorization, Exception Handling, Caching, etc., to our application. In ASP.NET Core
Applications, Filters allow us to execute cross-cutting logic in the following ways:
1. Before an HTTP request is handled by a controller action method.
2. After an HTTP request is handled by a controller action method.
3. After the response is generated but before it is sent to the client.
We have already discussed in Routing that when a client makes a request, that request
comes to the Routing Engine, and then the Routing Engine navigates that Request to the
Controller Action Method. So, the Controller action method will handle the incoming
request and send the response back to the client who initially made the request, as shown
in the image below.

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

Explain MVC (Model-View-Controller) in general?


This is one of the most frequently asked ASP.NET MVC Interview Questions. So here we
will discuss what is MVC design pattern is and what are the role and responsibilities of the
Model, View, and Controller in detail.
MVC is an architectural software design pattern that is used for developing interactive
applications where there would be user interaction involved and based on the user
interaction some event handling occurs. So, this Model View Controller (MVC) design
pattern is not only used for developing web-based applications but it can also be used for
Desktop or mobile-based applications where there are user interactions involved, and
based on the user interaction some event handling occurs.
This MVC (Model-View-Controller) design pattern was introduced in the 1970s which
basically divides an application into 3 major components such as Model,
View, and Controller. The main objective of the MVC design pattern is the separation
of concerns. It means the domain model and business logic are separated from
the user interface (i.e. view). Thus, maintenance and testing of the application become
simpler and easier.

The Model in MVC Design Pattern:


The Model is the component in the MVC design pattern which manages that data i.e. state
of the application in memory. It represents a set of classes that holds the business data
as well as business logic, validation logic, and data access logic to manage the business
data. For example, an Employee object (Model) might retrieve the data from a database,
operate on it, validate the data, and then write the updated information back to an
Employee table in the database. So the model is basically used to contain business
(domain) data and business logic.
The View in MVC Design Pattern:
The view is the component in the MVC design pattern which represents the user interface
with which the end-user can interact. Basically, the view is used to render the domain data
(i.e. business data). It creates the user interface with data from the model with which the
end-user can interact. An example would be an edit view of a product table that displays
text boxes, dropdown lists, and checkboxes based on the current state of a Product object.
The Controller in MVC Design Pattern:
The Controller is the component in the MVC design pattern which contains the control flow
logic. It is the one that will interact with both the models and views to control the flow of
application execution. So, the controller component responds to user actions. Based on
the user actions, the respective controller works with the model and view and sends
responses back to the user.
What is ASP.NET MVC?
In many ASP.NET MVC interviews, they asked this question to check whether you know
the difference between MVC and ASP.NET MVC. The first thing is first. So, remember
both ASP.NET MVC and MVC are two different things altogether.
The ASP.NET MVC is an open-source web application development framework from
Microsoft that is based on the MVC (Model-View-Controller) architectural design pattern
which provides a clean separation of code. This is the most customizable and extensible
platform or framework provided by Microsoft.
So, the point that you need to remember is, ASP.NET MVC is a
Framework whereas MVC is a Design Pattern and the ASP.NET MVC Framework is
based on MVC Design Pattern.
What are Model, View, and Controller from ASP.NET MVC Point of
view?
We already discussed What are Model, View, and Controllers from the MVC Design
pattern Point of View. So, let discuss What are Model, View, and Controllers from
ASP.NET MVC Point of view.
Model in ASP.NET MVC:
1. In MVC, the models are basically C#.NET or VB.NET classes.
2. The Models are basically used to manage the business data and business
logic.
3. This is the component that can be accessed by both the controller and view.
4. The model component can be used by a controller to pass the data to a
view.
5. It can also be used by a view, in order to display the data the in page
(HTML output)
View in ASP.NET MVC:
1. In the ASP.NET MVC application, the views are nothing but the cshtml or
vbhtml pages without having a code-behind file.
2. All page specific HTML generation and formatting can be done inside view.
3. A request to view can only be made from a controller’s action method.
4. The view is only responsible for displaying the data.
5. By default, views are stored in the Views folder of an ASP.NET MVC
application.
The controller in ASP.NET MVC:
1. In ASP.NET MVC, the controller is basically a C# or VB.NET class that
inherits from System.Web.Mvc.Controller.
2. This is the component that has access to both the Models and Views in
order to control the flow of the application execution.
3. The Controller class contains action methods that are going to respond to
the incoming URL.
4. A controller can access and use the model classes to pass the data to a
view.
5. By default, controllers have stored in the Controllers folder an ASP.NET
MVC application.
What are the Advantages of ASP.NET MVC?
This is one of the ASP.NET MVC questions asked in the interview to check whether you
know why you are using MVC or not. So let us discuss what are the advantages of using
ASP.NET MVC or you can say why we need to use ASP.NET MVC to develop a web
application.
1. The ASP.NET MVC Views are lightweight as compared to ASP.NET Web
Forms because it does not use view state or any server-based forms or
controls to render the data.
2. As we are separating the view from the rest of the application which
enables us to change of view (technology) in the future without affecting the
rest of the application. For example, we might have views in Silverlight or
HTML5.
3. Each developer based on his expertise or experience can work on
different parts of the application without stepping on each other toes. For
example, one developer can work on the view while the second developer
can work on the controller logic and the third developer can focus on the
business logic in the model by interacting with the database.
4. With the introduction of Attribute Routing, now it is very easy to create
Restful or User-friendly URL’s which enable SEO to rank your page high.
5. The ASP.NET MVC provides better support for test-driven development
(TDD). This is because we can focus on one aspect at a time i.e. we can
focus on the view without worrying about business logic as each component
can be developed independently and also can be mocked easily.
6. As the MVC design pattern divides the application into three major
components such as Model, View, and Controller which make it easier to
manage the application complexity.
7. MVC framework components were designed to be pluggable and
extensible and therefore can be replaced or customized in the future very
easily
8. AS the MVC framework is built on top of ASP.NET, so, we can use
most of the ASP.NET features such as the authentication and authorization
scenarios, membership and roles, caching, session, and many more.
What is the difference between 3-layer architecture and MVC
architecture?
This is one of the frequently asked ASP.NET MVC Interview Questions. So, let us
understand the differences between them.
The 3-layer architecture separates the application into 3 components which consist of the
Presentation Layer, Business Layer, and Data Access Layer. In 3-layer architecture, the
user is going to interacts with the Presentation layer only. 3-layer is a linear architecture.
The MVC architecture separates the application into three major components such as
Model, View, and Controller. In MVC architecture, the user is going to interacts with the
controller with the help of a view. MVC is a triangle architecture.
MVC does not replace 3-layer architecture. Typically MVC and 3-layer architecture are
used together and the MVC Design Pattern acts as the Presentation layer of the
application.
What are the differences between ASP.NET MVC and ASP.NET
WebForms?
This is one of the Frequently asked ASP.NET MVC interview questions and answers.
The ASP.NET Web Forms uses the Page controller pattern approach for rendering the
layout whereas ASP.NET MVC uses the Front controller approach for rendering the
layout. In the case of the Page controller Pattern approach, every aspx page having its
own controller i.e. the code-behind file which is used to process the incoming request.
Whereas, in ASP.NET MVC, a common controller can process the requests for all pages.
If you are visiting ASP.NET forums and communities, we will find the following questions
frequently i.e.
1. What is the difference between ASP.NET MVC and ASP.NET
WebForms?
2. Is ASP.NET MVC going to replace ASP.NET WebForms?
The first and important thing that you need to remember is, the ASP.NET MVC Framework
is not going to replace the ASP.NET WebForms Framework. Both technologies exist and
both can be used to develop ASP.NET applications. Here we are going to discuss, what
are the advantages and disadvantages of both these technologies one over another.
1. In ASP.NET WebForms there is no separation of concerns as every page
(.aspx) has its own controller (i.e. code-behind i.e. aspx.cs/.vb file). As a
result, both are tightly coupled. Whereas the main objective of ASP.NET
MVC is the clean separation of concerns as View and Controller are cleanly
separate and also they are not tightly coupled.
2. Because of the tightly coupled behavior in ASP.NET Web Forms (i.e.
.aspx page and its code-behind file), unit testing is really a nightmare for a
developer. Whereas in ASP.NET MVC unit testing is achieved very easily
as they are not tightly coupled.
3. ASP.NET Web Forms follows a Page Life cycle. Whereas in ASP.NET
MVC there is no such Page Life cycle like WebForms. The request cycle is
simple in the ASP.NET MVC model.
4. ASP.NET MVC views are lightweight, as they do not use ViewState
whereas ASP.NET Web Forms pages are not lightweight as they use
ViewState.
5. Complex applications can be easily managed in ASP.NET MVC because
of the separation of concerns. Different components of the application can
be divided into Model, View, and Controller.
6. ASP.NET web form has file-based URLs means the file name that exists
in the URLs must have its physical existence whereas ASP.NET MVC has
route-based URLs means URLs are divided into controllers and actions and
moreover it is based on controller not on physical file.
7. ASP.NET web form has Master Pages for consistent looks and feels
whereas ASP.NET MVC has Layouts for consistent looks and feels.
8. ASP.NET web form has User Controls for code re-usability
whereas ASP.NET MVC has Partial Views for code re-usability.
9. ASP.NET Web Form is not Open Source whereas ASP.NET Web MVC is
an Open Source.
10. ASP.NET Web Form has server controls whereas ASP.NET MVC has
HTML helpers.
Can you please explain the request flow in the ASP.NET MVC
framework?
This is one of the Frequently asked ASP.NET MVC interview questions and answers. If
you are going for an ASP.NET MVC interview, then you definitely face this question i.e.
Explain the Request Flow of the ASP.NET MVC Application. So here you need to explain
how a request is handled in the ASP.NET MVC framework. This is one of the frequently
asked ASP.NET MVC Interview questions.
The Request flow for the ASP.NET MVC framework is as follows:
In the ASP.NET MVC application when the client makes a request (i.e. HTTP Request)
for a resource from the browser then that request is first Received by the Routing Engine.
Once the Routing engine receives the HTTP Request, then it figures out the URL Pattern
of the incoming request and checks if that URL pattern is present in the Route table. If
there is no matching URL Pattern found in the routing table for the incoming HTTP request
URL Pattern, then it simply returns a 404 HTTP status code to the client. If it found a
matching URL pattern for the incoming request in the Route Table, then it fetches the
corresponding handler information and forwards the request to the appropriate controller
and action method.
The controller then plays its role and executes the action method. While executing the
action method if needed then it will work with the model component in order to serve the
request. Once it works with the model component, then it selects a view and passes that
model data to that view, and that view will transform the model data and generates an
appropriate response that is rendered to the client.
The point that you need to be noted is that the difference between WebForms and MVC
is that in MVC we don’t have the Page concept whereas, in Legacy like ASP.NET Web
Forms application, we do have pages like .aspx. So if your question is, Then how do the
requests are been pointed in MVC? The answer is via Controller. This special class is
responsible for generating the response and sending the data back to the client.
For instance, the URL http://www.xyz.net/Book/Create Says that it is requesting for the
Controller class name “Book” and the Action Method name called “Create”.
What are the important namespaces used in ASP.NET MVC?
This question is not that important, but you should what are the important namespaces
you used in the ASP.NET MVC application. The following are some of the important
namespaces:
1. System.Web.Mvc – This namespace contains classes and interfaces that
support the MVC pattern for ASP.NET Web applications. This namespace
includes classes that represent controllers, controller factories, action
results, views, partial views, and model binders.
2. System.Web.Mvc.Ajax – This namespace contains classes that support
Ajax scripting in an ASP.NET MVC application. The namespace includes
support for Ajax scripts and Ajax option settings as well.
3. System.Web.Mvc.Html – This namespace contains classes that help
render HTML controls in an MVC application. This namespace includes
classes that support forms, input controls, links, partial views, and
validation.
What is ViewModel in ASP.NET MVC?
In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in
the strongly-typed view. It is used to pass data from the controller to a strongly-typed view.
Key Points about ViewModel
1. ViewModel contains fields that are represented in the view (for LabelFor,
EditorFor, DisplayFor helpers).
2. ViewModel can have specific validation rules using data annotations.
3. ViewModel can have multiple entities or objects from different data models
or data source.
What are Action methods in ASP.NET MVC?
All public methods of a Controller in ASP.NET MVC application that respond to the
incoming URL are considered as Action Methods.
Controller actions are methods defined in the controller class and responsible to perform
required operations on the user’s inputs like form values, query strings values, etc. with
the help of the Model and passing the results back to the View. Asp.net MVC has the
following built-in ActionResults Type and Helper methods:
1. ViewResult – Returns a ViewResult which renders the specified or default
view by using the controller View() helper method.
2. PartialViewResult – Returns a PartialViewResult which renders the
specified or default partial view (means a view without its layout) by using
the controller PartialView() helper method.
3. RedirectResult – Returns a RedirectResult which Issues an HTTP 301 or
302 redirection to a specific URL by using controller Redirect() helper
method.
4. RedirectToRouteResult – Returns a RedirectToRouteResult which
Issues an HTTP 301 or 302 redirection to an action method or specific route
entry by using controller RedirectToAction(), RedirectToActionPermanent(),
RedirectToRoute(), RedirectToRoutePermanent() helper methods.
5. ContentResult – Returns a ContentResult which renders raw text like
“Hello, DotNet Tutorials!” by using the controller Content() helper method.
6. JsonResult – Returns a JsonResult which serializes an object in JSON
format ( like as “{ “Message”: Hello, World! }”) and renders it by using
controller Json() helper method.
7. JavaScriptResult – Returns a JavaScriptResult which renders a snippet
of JavaScript code like as “function hello() { alert(Hello, World!); }” by using
controller JavaScript() helper method. This is used only in AJAX scenarios.
8. FileResult – Returns a FileResult which renders the contents of a file like
PDF, DOC, Excel, etc. by using the controller File() helper method.
9. EmptyResult – Returns no result returned by an action. This has no
controller helper method.
10. HttpNotFoundResult – Returns an HttpNotFoundResult which renders a
404 HTTP Status Code response by using controller HttpNotFound() helper
method.
11. HttpUnauthorizedResult – Returns an HttpUnauthorizedResult which
renders a 401 HTTP Status Code (means “not authorized”) response. This
has no controller helper method. This is used for authentication (forms
authentication or Windows authentication) to ask the user to log in.
12. HttpStatusCodeResult – Returns an HttpStatusCodeResult which
renders a specified HTTP code response. This has no controller helper
method.
Note: All public methods of a Controller in an ASP.NET MVC application are considered
as Action Methods by default. If we want our controller to have a Non-Action Method, we
need to explicitly mark it with the NonAction attribute as follows:
What is ActionResult and how is it different from others?
The ActionResult class is the base class for all action results. An action result can be of
type ViewResult, JsonResult, RedirectResult and so on. Hence, when your action method
returns multiple results based on different conditions, ActionResult is the best choice.
Since it can return any type of result.

How to make a Non-Action method in ASP.NET MVC?


By default, the ASP.NET MVC framework treats all public methods of a controller class as
action methods. If you do not want a public method to be an action method, you must
mark that method with the NonActionAttribute attribute.
[NonAction]
public void DoSomething()
{
// Method logic
}
Can you change the action method name?
We can also change the action method name by using the ActionName attribute. Now
action method will be called by the name defined by the ActionName attribute.
[ActionName("DoAction")]
public ActionResult DoSomething()
{
//TODO: return View();
}
Now, DoSomething action will be identified and called by the name DoAction.
How to restrict an action method to be invoked only by HTTP GET,
POST, PUT or DELETE?
By default, each and every action method can be invoked by an HTTP request (i.e. GET,
PUT, POST, and DELETE). But you can restrict an action to be invoked only by a specific
HTTP request by applying HttpGet or HttpPost or HttpPut or HttpDelete attribute.
If you want to restrict an action method for HTTP Get request only then decorate it with
HttpGet action method selector attribute as given below:
[HttpGet]
public ActionResult Index()
{
//TODO:
return View();
}
How to determine an action method is invoked by HTTP GET or POST?
By using the HttpMethod property of HttpRequestBase class, you can find out whether an
action is invoked by HTTP GET or POST.
public ActionResult Index(int? id)
{
if (Request.HttpMethod == "GET")
{
//TODO:
}
else if (Request.HttpMethod == "POST")
{
//TODO:
}
else
{
//TODO:
}
return View();
}
How to determine an AJAX request?
We can determine an AJAX request by using Request.IsAjaxRequest() method. It will
return true if the request is an AJAX request else returns false.
public ActionResult DoSomething()
{
if (Request.IsAjaxRequest())
{
//TODO:
}
return View();
}
What is Child action and how to invoke it?
Suppose we have a scenario where we have one action method and we don’t want that
action method to be invoked via URL rather we want that action method to be invoked by
other actions (from parent views) of our application. Then in such
scenarios, ChildActionOnly Attribute can be handy. So, when we decorate an action
method with the ChildActionOnly attribute, then it is called child action in ASP.NET MVC
Application and child action methods are only accessible by a child request. That means
once an action method becomes a child action, then it will not respond to the URL requests
rather it will be invoked by other action methods of your application.
So, an action method that is decorated with the ChildActionOnly attribute cannot be
called independently. It always will be called within a parent view otherwise it would give
an error.
[ChildActionOnly]
public ActionResult MenuBar()
{
//TODO:
return PartialView();
}
A child action is invoked by using @Html.RenderAction or @Html.Action helper methods
from inside of a view.
What are Partial Views in ASP.NET MVC and it’s needed?
This is one of the Frequently asked ASP.NET MVC interview questions and answers. A
partial view is like user control in ASP.NET Webforms that are used for code re-usability.
Partial views help us to reduce code duplication. Hence partial views are reusable views
like Header and Footer views. We can use the partial view to display blog comments,
product category, social bookmarks buttons, a dynamic ticker, calendar, etc.
It is best practice to create a partial view in the shared folder and the partial view name is
preceded by “_”, but it is not mandatory. The “_” before view name specifies that it is a
reusable component i.e. partial view.
What are the Layouts in ASP.NET MVC?
Layouts are used to maintain a consistent look and feel across multiple views within the
ASP.NET MVC application. As compared to Web Forms, layouts serve the same purpose
as master pages but offer a simple syntax and greater flexibility. A basic structure of layout
is given below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody() @Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
You can use a layout to define a common template for your site. A layout can be
declared at the top of view as:
@{
Layout = "~/Views/Shared/SiteLayout.cshtml";
}
What are Sections in ASP.NET MVC?
A section allows us to specify a region of content within a layout. It expects one
parameter which is the name of the section. If you don’t provide that, an exception will
be thrown. A section on a layout page can be defined by using the following code.
@section header{ <h1>Header Content</h1> }
You can render the above-defined section header on the content page as given below:
@RenderSection(“header”)
By default, sections are mandatory. To make sections optional just provide the second
parameter value as false, which is a Boolean value.
@RenderSection(“header”,false)
Note: A view can define only those sections that are referred to in the layout page
otherwise an exception will be thrown.
What are RenderBody and RenderPage in ASP.NET MVC?
This is one of the Frequently asked ASP.NET MVC interview questions and answers.
RenderBody method exists in the Layout page to render child page/view. It is just like the
ContentPlaceHolder on the master page. A layout page can have only one RenderBody
method.
<body>
@RenderBody()
@RenderPage("~/Views/Shared/_Header.cshtml")
@RenderPage("~/Views/Shared/_Footer.cshtml")
@RenderSection("scripts", false)
@section scripts{
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
}
</body>
The reader page method also exists in the Layout page to render another page that exists
in your application. A layout page can have multiple RenderPage methods.
@RenderPage(“~/Views/Shared/_Header.cshtml”)
What are the Styles.Render and Scripts.Render?
Style.Render is used to render a bundle of CSS files defined within BundleConfig.cs files.
Styles.Render create style tag(s) for the CSS bundle. Like Style.Render, Scripts.Render
is also used to render a bundle of Script files by rendering script tag(s) for the Script
bundle.
public class BundleConfig
{
// For more information on bundling, visit
http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then,
when you're
// ready for production, use the build tool at http://modernizr.com to pick only the
tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
The Styles.Render and Scripts.Render generate multiple styles and script tags for each
item in the CSS bundle and Script bundle when optimizations are disabled. When
optimizations are enabled, Styles.Render and Scripts.Render generate a single style and
script tag to a version-stamped URL which represents the entire bundle for CSS and
Scripts.
How to enable and disable optimizations in ASP.NET MVC?
We can enable and disable optimizations by setting the EnableOptimizations property of
BundleTable class to true or false within Global.asax.cs file as shown below.

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.

Can you remove the default View Engine in ASP.NET MVC?


Yes, we can remove default view engines (i.e. Razor and WebForm) provided by
ASP.NET MVC.
What is the difference between the Razor and WebForm engine?
This is one of the Frequently asked ASP.NET MVC Interview Questions and Answers.
The main differences between ASP.NET Web Form and ASP.NET MVC are given below:
1. Razor Engine was introduced with ASP.NET MVC3 Framework. It is a
new markup syntax whereas Web Form View Engine is the default View
Engine from the beginning of ASP.NET MVC Framework.
2. The Razor Engine belongs to System.Web.Razor namespace whereas
the Webform Engine belongs
to System.Web.Mvc.WebFormViewEngine namespace.
3. Razor View Engine has new and advances syntax that is compact,
expressive, and reduces typing whereas Web Form View Engine has the
same syntax as WebForms.
4. The Razor View Engine syntaxes are easy to learn as well as much
cleaner than the Web Form View Engine syntax. It uses @ symbol to switch
between the C# code and HTML code whereas the Web Form View Engine
syntaxes are borrowed from ASP.NET WebForms. The Webform uses <%
and %> delimiters to switch between the C# and HTML code.
5. By default, the Razor View Engine prevents Cross-Site Scripting Attacks
(XSS attacks). That means it encodes the script or HTML tags before
rendering to the view. On the other hand, the Web Form View Engine does
not prevent Cross-Site Scripting Attacks. That means any script saved in
the database will be fired while rendering the page.
6. The Razor View Engine doesn’t support the design mode in the visual
studio. That means we cannot see how our page looks at the time
developing. Whereas the Web Form View Engine supports the design mode
in the visual studio. That means we can see how our page looks at the time
of development without running the application.
What are HTML Helpers in ASP.NET MVC?
This is one of the Frequently asked ASP.NET MVC Interview Questions and Answers.
The HTML Helpers in ASP.NET MVC application are nothing but methods returning an
HTML string that can render an HTML tag. For example, a link, a textbox, a label, or other
form elements.
Developers who have worked with ASP.NET Web Forms can map the HTML helper
methods to Web Form Controls because both serve the same purpose. But HTML helpers
are comparatively lightweight because they don’t have view state and event like Web Form
Controls. Along with the built-in HTML helpers, it is also possible to create our own custom
helper methods to fulfill our specific purpose. For example, we can create custom HTML
Helpers to render more complex content such as a menu strip or an HTML table for
displaying database data.
Note: The HTML helpers are implemented as extension methods.
Is it mandatory to use HTML helpers?
No, we can type the required HTML but using HTML helpers will greatly reduce the amount
of HTML that we have to write in a view. Views should be as simple as possible. All the
complicated logic to generate a control can be encapsulated into the helper to keep views
simple.
What is the Difference between Html.TextBox and Html.TextBoxFor?
This is one of the Frequently asked ASP.NET MVC Interview Questions and Answers.
So let us discuss this question in detail.
Advertisements
Html.TextBox is not a strongly typed helper method and hence it doesn’t require a
strongly typed view. That means we can hardcode whatever name we want. On the other
hand Html.TextBoxFor is a strongly typed HTML Helper method and hence it requires a
strongly typed view and the name is given by using the lambda expression.
The Strongly typed HTML helper methods provide compile-time error checking. In most of
the real-time application, we use strongly typed views, so we prefer to use
Html.TextBoxFor over their counterpart HTML.TextBox.
The most important point that we need to remember is, whether we use the Html.TextBox
or Html.TextBoxFor helper method the end result is going to be the same that is they
produce the same HTML. Strongly typed HTML helpers are introduced in ASP.NET MVC
MVC2.
What is the Validation Summary in the ASP.NET MVC Application?
The ValidationSummary HTML Helper method displays all the validation errors of the
ModelState dictionary in an unordered list. This ValidationSummary HTML Helper method
accepts a boolean value (i.e. true or false) and based on the boolean value it displays the
errors. When the boolean parameter value is set to true, then it shows only the model-
level errors and excludes model property-level errors (i.e. any errors that are associated
with a specific model property). When the Boolean value is set to false, then it is going to
shows both model-level and property-level errors.
Suppose, you have the following lines of code somewhere in the controller action
rendering a view:
ModelState.AddModelError(“”, “This is Model-level error!”);
ModelState.AddModelError(“Title”, “This Model property-level error!”);
Advertisements
In the first statement, there is no key is to associate with the error. In the second statement,
there is a key with the name “Title” that is associated with the error for the model property
Name.
@Html.ValidationSummary(true) @*//shows model-level errors*@
@Html.ValidationSummary(false) @*//shows model-level and property-level
errors*@
Hence, when the boolean type value is set to true then the ValidationSummary HTML
Helper method will display only the model-level errors and exclude property-level errors.
If we set the value to false, then it will display both Model-level and property-level errors.
What is unobtrusive AJAX?
ASP.NET MVC Framework supports unobtrusive Ajax. The unobtrusive Ajax means, we
can use the HTML Helper methods to define our Ajax features, rather than adding blocks
of code throughout our views.
What is Cross-Domain AJAX?
This is one of the Frequently asked ASP.NET MVC Interview Questions and Answers. By
default, a web browser allows AJAX calls only to the same domain i.e. site hosted server.
This restriction helps us to prevent various security issues like cross-site scripting
(XSS) attacks. But, sometimes we need to interact with externally hosted API(s) like
Twitter or Google. Hence to interact with these external API(s) or services our web
application must support JSONP requests or Cross-Origin Resource Sharing (CORS).
By default, ASP.NET MVC does not support JSONP or Cross-Origin Resource
Sharing. For this, you need to do a little bit of coding and configuration.
What is Caching?
Caching is the most important aspect of a high-performance web application. Caching
provides a way of storing frequently accessed data and reusing that data. Practically, this
is an effective way of improving the web application’s performance.
Advertisements
When to use Caching in ASP.NET MVC Application?
1. Use caching for contents that are accessed frequently.
2. Avoid caching for contents that are unique per user.
3. Avoid caching for contents that are accessed infrequently/rarely.
4. Use the VaryByCustom function to cache multiple versions of a page
based on customization aspects of the request such as cookies, role,
theme, browser, and so on.
5. For efficient caching use a 64-bit version of Windows Server and SQL
Server.
6. For database caching make sure your database server has sufficient RAM
otherwise, it may degrade the performance.
7. For caching of dynamic contents that change frequently, define a short
cache–expiration time rather than disabling caching.
What are the advantages of caching in ASP.NET MVC Application?
We are getting the following advantages of using caching:
1. Reduce hosting server round-trips
2. When content is cached at the client or in proxies, it causes the minimum
request to the server.
3. Reduce database server round-trips
4. When content is cached at the web server, it can eliminate the database
request.
5. Reduce network traffic
6. When content is cached at the client-side, it also reduces the network
traffic.
7. Avoid time-consumption for regenerating reusable content
8. When reusable content is cached, it avoids the time consumption for
regenerating reusable content.
9. Improve performance
10. Since cached content reduces round-trips, network traffic and avoids time
consumption for regenerating reusable content which causes a boost in the
performance.
What is the Output Caching in ASP.NET MVC Application?
The OutputCache filter allows you to cache the data that is the output of an action method.
By default, this attribute filter caches the data until 60 seconds. After 60 sec, ASP.NET
MVC will execute the action method again and cache the output again.

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

public class BlogModel


{
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[AllowHtml]
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
}
What is loose coupling and how is it possible in MVC Design Pattern?
One of the most important features of the MVC design pattern is that it enables the
separation of concerns. Hence you can make your application’s components independent
as much as possible. This is known as loose coupling and it makes testing and
maintenance of our application easier. Using Dependency Injection you can make your
application’s components more loosely coupled.
What is Test-Driven Development (TDD)?
TDD is a methodology that says; write your tests first before you write your code. In TDD,
tests drive your application design and development cycles. You do not do the check-in
of your code into source control until your entire unit tests pass.
What are the commonly used tool for Unit Testing in ASP.NET MVC?
ASP.NET MVC has been designed for testability without dependencies on the IIS server,
on a database, or on external classes. There are the following popular tools for ASP.NET
MVC testing:
Advertisements
1. NUnit – This is the most popular unit testing framework for Microsoft.NET.
Its syntax is relatively simple and easy to use. It comes with a test runner
GUI and a command-line utility. NUnit is also available as a NuGet package
for download.
2. xUnit.NET – This provides a way to run automated unit tests. It is simple,
easily extended, and has a very clean syntax.
3. Ninject – This provides a way to wire up classes in your application.
4. Moq – This provides a framework for mocking interfaces and classes
during testing.

C# Interview Questions and Answers


C#.NET Interview Questions And Answers
In this article, I am going to discuss the most frequently asked 50 C# Interview Questions
and Answers. This is part 1 of the C# .NET Interview Questions and Answers article
series and hence in this article, we are going to discuss frequently asked basic C#
Interview Questions and Answers and in our upcoming articles, we will discuss the
experienced Interview questions. As part of this article, we are going to discuss the
following C# Interview Questions with Answers.

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

Why Do We Need to Learn SOLID Design Principles?


As developers, we start developing applications using our experience and knowledge. But
over time, the applications might cause bugs. We must alter the application design for
every change request or new feature request. After some time, we might need to put in a
lot of effort, even for simple tasks, which might require the full working knowledge of the
entire system. However, we can’t blame the change requests or new feature requests as
they are part of software development. We can’t stop them, and we can’t refuse them
either. So who is the culprit here? Obviously, it is the Design of the Application.
So, by considering the above problem and helping Students, Beginners, and
Professionals Software Developers who want to learn How to design good software using
SOLID Design Principles using C# Language in a quick time, I have decided to start a
series of articles on SOLID Design Principles with Real-time Examples.
What are the Main Reasons Behind Most Unsuccessful Applications?
The following are the Main Reasons Behind Most Unsuccessful Applications.
1. Putting More Functionalities on Classes. (In simple words, we put many
functionalities into the class even though they are unrelated to that class.)
2. Implementing Tight Coupling Between the Software Components (i.e.,
Between the Classes). If the classes depend on each other, changing one
class will also affect the other.
How to Overcome the Unsuccessful Application Development
Problems?
1. We need to use the Correct Architecture (i.e., MVC, Layered, 3-tier, MVP,
and so on) as per the Project Requirements.
2. As developers, we must follow the Design Principles (e.g., the SOLID
Principles, the ONIO Design Principles, etc.).
3. Again, we must choose the correct Design Patterns (Creational Design
Pattern, Structural Design Pattern, Behavioral Design Pattern, Dependency
Injection Design Pattern, Repository Design Pattern, etc.) per the project
requirements.
What are SOLID Design Principles?
The SOLID Design Principles are used to manage most of the Software Design
Problems we, as developers, generally encounter in our day-to-day programming. These
design principles are tested and proven mechanisms to make software designs more
understandable, flexible, and maintainable. As a result, if we follow these principles while
designing our applications, we can develop better applications.
SOLID Design Principles represent five Design Principles used to make software designs
more understandable, flexible, and maintainable. The Five SOLID Design Principles are
as follows:
1. S stands for the Single Responsibility Principle, also known
as SRP. This Principle states that each software module or class should
have only one reason to change. In other words, each module or class
should have only one responsibility.
2. O stands for the Open-Closed Principle, also known as OSP. The Open-
Closed Principle states that software entities, such as modules, classes,
functions, etc., should be open for extension but closed for modification.
3. L stands for the Liskov Substitution Principle, also known as LSP. This
Principle states that the object of a derived class should be able to replace
an object of the base class without causing any errors in the system or
modifying the behavior of the base class. That means the child class objects
should be able to replace parent class objects without changing the
correctness or behavior of the program.
4. I stand for the Interface Segregation Principle, also known as ISP. This
Principle states that Clients should not be forced to implement any methods
they don’t use. Rather than one fat interface, numerous little interfaces are
preferred based on groups of methods, with each interface serving one
submodule.
5. D stands for Dependency Inversion Principle, also known as DIP. This
Principle states that high-level modules/classes should not depend on low-
level modules/classes. Both should depend upon abstractions. Secondly,
abstractions should not depend upon details. Details should depend upon
abstraction

1. What is COM and what are the disadvantages of COM?


2. What .NET Represents?
3. What is a Framework and what does the .NET Framework provide?
4. Explain CLR and its Execution Process.
5. What is exactly .NET?
6. What are the language and its need?
7. What are Technology and its need?
8. What is Visual Studio?
9. Explain about BCL.
10. What is the Just-In-Time (JIT) compilation?
11. What are Metadata and an assembly?
12. What are the differences between managed code and unmanaged code?
13. What is C#?
14. What is the difference between an EXE and a DLL?
15. What’s the difference between IEnumerable<T> and List<T>?
16. Why is class an abstract data type?
17. What are the new features introduced in C# 7?
18. Why should you override the ToString() method?
19. What is the difference between string keyword and System.String
class?
20. Are string objects mutable or immutable in C#?
21. What do you mean by String objects are immutable?
22. What is a verbatim string literal and why do we use it?
23. How do you create empty strings in C#?
24. What is the difference between System.Text.StringBuilder and
System.String?
25. How do you determine whether a String represents a numeric value?
26. What is the difference between int.Parse and int.TryParse methods?
27. What are Properties in C#? Explain with an example.
28. What are the different types of properties available in C#?
29. What are the advantages of using properties in C#?
30. What is a static property? Give an example.
31. What is Virtual Property in C#? Give an example.
32. What is an Abstract Property in C#? Give an example.
33. Can you use virtual, override, or abstract keywords on an accessor of a
static property?
34. What are the 2 broad classifications of data types available in C#?
35. How do you create user-defined data types in C#?
36. Difference between int and Int32 in C#
37. What are the differences between value types and reference types?
38. What do you mean by casting a data type?
39. What are the 2 kinds of data type conversions available in C#?
40. What is the difference between an implicit conversion and an explicit
conversion?
41. What is the difference between int.Parse and int.TryParse methods?
42. What is Boxing and Unboxing in C#?
43. What happens during the process of boxing?
44. What are Access Modifiers in C#?
45. Can we use all access modifiers for all types?
46. Can derived classes have greater accessibility than their base types?
47. Can the accessibility of a type member be greater than the accessibility
of its containing type?
48. Can destructors have access modifiers?
49. What do protected internal access modifiers mean?
50. Can you specify an access modifier for an enumeration?
What is COM?
1. COM stands for Component Object Model.
2. COM is one of Microsoft’s technologies. Using this technology we can
develop windows applications as well as web applications.
In earlier COM, VB is the programming language that is used to implement windows
applications and ASP is used to implement web applications.
What are the disadvantages of COM?
The major two disadvantages of COM is
1. Incomplete object-oriented programming means it will not support all the
features of OOPs.
2. Platform dependent means COM applications can run on only Windows OS.
What .NET Represents?
1. NET stands for Network Enabled Technology.
2. In .NET dot (.) refers to object-oriented and NET refers to the internet.
So the complete .NET means through object-oriented we can implement internet
applications.
What is a Framework?
A framework is a software. Or we can say that a framework is a collection of many small
technologies integrated together to develop applications that can be executed anywhere.
What does the .NET Framework provide?
.NET Framework provides two things such as
1. BCL (Base Class Libraries)
2. CLR (Common Language Runtime)
Explain BCL.
1. Base Class Libraries are designed by Microsoft.
2. Without BCL we can’t write any code in .NET so BCL also was known as
the Building block of Programs of .NET.
3. These are installed into the machine when we installed the .NET
framework into the machine.
BCL contains predefined classes and these classes are used for the purpose of
application development. The physical location of BCL is C:\Windows\assembly
Explain CLR and its Execution process.
CLR is the core component under the .NET framework which is responsible for
converting MSIL code into native code and then execution. Let us understand the
Execution flow of CLR with an example. Please have a look at the following code.

In .NET, the code is compiled twice.


1. In 1st compilation source code (High-Level Code) is compiled by the
respective language compiler and the language compiler generates
intermediate code which is also known as MSIL (Microsoft Intermediate
Language) or IL (Intermediate language code) Or Managed code.
2. In the 2nd compilation, MSIL is converted into Native Code (Machine code)
using CLR.
Always 1 compilation is slow and 2nd compilation is fast.
st

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

public string FirstName;

public string LastName;

public class MainClass

public static void Main()

Customer C = new 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

public string FirstName;

public string LastName;

public override string ToString()

return LastName + ", " + FirstName;

public class MainClass

public static void Main()

Customer C = new 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 ";

string s2 = "Second String";

// Concatenate s1 and s2. This actually creates a new

// string object and stores it in s1, releasing the

// reference to the original object.

s1 += s2;

System.Console.WriteLine(s1);

// Output: First String Second String


What will be the output of the following code?
string str1 = "Hello ";

string str2 = str1;

str1 = str1 + "C#";

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

string MultiLineText = @"This is multiline

Text written to be in
three lines.";

/* Output:

This is multiline

Text written to be in

three lines.

*/

string DoubleQuotesString = @"My Name is ""Pranaya.""";

//Output: My Name is "Pranaya."


Will the following code compile and run?
string str = null;
Console.WriteLine(str.Length);
The above code will compile but at runtime System.NullReferenceException will be
thrown.
How do you create empty strings in C#?
Using string.empty as shown in the example below.
string EmptyString = string.empty;
What is the difference between System.Text.StringBuilder and
System.String?
This is one of the frequently asked C#.NET Interview Questions. Objects of type
StringBuilder are mutable whereas objects of type System.String is immutable. As
StringBuilder objects are mutable, they offer better performance than string objects of type
System.String. The StringBuilder class is present in System.Text namespace where String
class is present in System namespace.
How do you determine whether a String represents a numeric value?
To determine whether a String represents a numeric value, we can use
the TryParse method as shown in the example below. If the string contains non-numeric
characters or the numeric value is too large or too small for the particular type you have
specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns
true and sets the out parameter to the numeric value of the string.
string str = "One";

int i = 0;

if(int.TryParse(str,out i))

Console.WriteLine("Yes string contains Integer and it is " + i);

else
{

Console.WriteLine("string does not contain Integer");

}
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

// Private fileds not accessible outside the class.

private string _firstName = string.Empty;

private string _lastName = string.Empty;

private string _coutry = string.Empty;

// public FirstName property exposes _firstName variable

public string FirstName

get

return _firstName;
}

set

_firstName = value;

// public LastName property exposes _lastName variable

public string LastName

get

return _lastName;

set

_lastName = value;

// FullName property is readonly and computes customer full name.

public string FullName

get

return _lastName + ", " + _firstName;

}
}

//Country Property is Write Only

public string Country

set

_coutry = value;

class MainClass

public static void Main()

Customer CustomerObject = new Customer();

//This line will call the set accessor of FirstName Property

CustomerObject.FirstName = "David";

//This line will call the set accessor of LastName Property

CustomerObject.LastName = "Boon";

//This line will call the get accessor of FullName Property

Console.WriteLine("Customer Full Name is : " + CustomerObject.FullName);

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

What is Virtual Property in C#? Give an example.


This is one of the most frequently asked C#.NET Interview Questions. A property that is
marked with a virtual keyword is considered virtual property. Virtual properties enable
derived classes to override the property behavior by using the override keyword. In the
example below FullName is a virtual property in the Customer class. The BankCustomer
class inherits from the Customer class and overrides the FullName virtual property. In the
output, you can see the overridden implementation. A property overriding a virtual property
can also be sealed, specifying that for derived classes it is no longer virtual.
class Customer

private string _firstName = string.Empty;

private string _lastName = string.Empty;

public string FirstName

get

return _firstName;

set

_firstName = value;
}

public string LastName

get

return _lastName;

set

_lastName = value;

// FullName is virtual

public virtual string FullName

get

return _lastName + ", " + _firstName;

class BankCustomer : Customer

// Overriding the FullName virtual property derived from customer class


public override string FullName

get

return "Mr. " + FirstName + " " + LastName;

class MainClass

public static void Main()

BankCustomer BankCustomerObject = new BankCustomer();

BankCustomerObject.FirstName = "David";

BankCustomerObject.LastName = "Boon";

Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);

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

abstract class Customer

private string _firstName = string.Empty;


private string _lastName = string.Empty;

public string FirstName

get

return _firstName;

set

_firstName = value;

public string LastName

get

return _lastName;

set

_lastName = value;

// FullName is abstract

public abstract string FullName


{

get;

class BankCustomer : Customer

// Overriding the FullName abstract property derived from customer class

public override string FullName

get

return "Mr. " + FirstName + " " + LastName;

class MainClass

public static void Main()

BankCustomer BankCustomerObject = new BankCustomer();

BankCustomerObject.FirstName = "David";

BankCustomerObject.LastName = "Boon";

Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);

}
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

public static void Main()

{
}

}
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

public void Save();

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

Inheritance and Interface Interview Questions in C#


with Answers
In this article, I am going to discuss the most frequently asked Inheritance and Interface
Interview Questions and Answers in C#. Please read our previous article where we
discussed the most frequently asked C# Interview Questions and Answers. As part of
this article, we are going to discuss the following Inheritance and Interface Interview
Questions in C# with answers.
Advertisements

1. What are the 4 pillars of any object-oriented programming language?


2. Do structs support inheritance in C#?
3. What is the main advantage of using inheritance in C#?
4. Does C# support multiple class inheritance?
5. Why does C# not support multiple class inheritance?
6. What are the differences between interfaces and abstract classes?
7. When do you choose interface over an abstract class or vice versa?
8. What are the advantages of using interfaces?
9. Can an Interface contain fields?
10. What is the difference between class inheritance and interface
inheritance?
11. Can an interface inherit from another interface?
12. Can you create an instance of an interface?
13. What do you mean by “Explicitly Implementing an Interface”? Give an
example?
14. When to use Interface?
What are the 4 pillars of any object-oriented programming language?
1. Abstraction
2. Inheritance
3. Encapsulation
4. Polymorphism
Do structs support inheritance?
No, structs do not support inheritance, but they can implement interfaces.
What is the main advantage of using inheritance?
Code reuse
Is the following code legal?
class ChildClass : ParentClassA, ParentClassB

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

class Demo : Car

// Explicit implementation of an interface member

void Car.Drive()

Console.WriteLine("Drive Car");

static void Main()

Demo DemoObject = new Demo();

//DemoObject.Drive();

// Error: Cannot call explicitly implemented interface method

// using the class object.

// Type cast the demo object to interface type Car

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

Abstract and Sealed Class Interview Questions in C#


Abstract and Sealed Class Interview Questions in C#
In this article, I am going to discuss the most frequently asked Abstract and Sealed Class
Interview Questions in C# with Answers. Please read our previous article where we
discussed the most frequently asked Interface and Inheritance Interview Questions
and Answers in C#. As part of this article, we are going to discuss the following Abstract
and Sealed Class Interview Questions in C# with answers.
Advertisements
1. When to use Abstract Classes in C#?
2. What is an Abstract Class?
3. Can you create an instance of an abstract class?
4. What is a Sealed Class?
5. What is the abstract method in C#?
6. When to use the abstract method?
7. Can a sealed class be used as a base class?
8. Can an abstract class have a constructor? If so what is the use?
9. We cannot create an instance of an abstract class. So, what is the use of
a constructor in an abstract class?
10. An abstract method in an abstract class does not have any
implementation, so what is the use of calling it from the abstract class
constructor?
11. When should a class be declared as abstract?
12. When should a method be declared as sealed?
13. What is the difference between the private and sealed method?
14. When should a class be declared as sealed?
15. What are the differences between an abstract class and a sealed class?
16. Why should the method have an abstract keyword if it does not have the
body?
17. What are the characteristics of an abstract class?
18. Why can the abstract class not be instantiated?
19. Who will provide the implementation (body) for abstract methods?
20. What type of members can we define in an abstract class?
21. Will abstract class members are created when a subclass object is
created?
22. How can we execute static and non-static concrete members of the
abstract class?
23. Can we declare the abstract method as static?
24. Can we declare the concrete class as abstract?
25. Explain the differences between overriding methods and abstract
methods?
26. What is the need for abstract classes in application development?
When to use Abstract Classes in C#?
When we have a requirement where our base class should provide the default
implementation of certain methods whereas other methods should be open to being
overridden by child classes use abstract classes.
What is an Abstract Class in C#?
A class that is declared by using the keyword abstract is called an abstract class. An
abstract class is a partially implemented class used for developing some of the operations
which are common for all next level subclasses. So it contains both abstract methods,
concrete methods including variables, properties, and indexers.
It is always created as a superclass next to the interface in the object inheritance hierarchy
for implementing common operations from the interface.
An abstract class may or may not have abstract methods. But if a class contains an
abstract method then it must be declared as abstract. The abstract class cannot be
instantiated directly. It’s compulsory to create/derive a new class from an abstract class in
order to provide the functionality to its abstract functions.
Can you create an instance of an abstract class?
No, abstract classes are incomplete and we cannot create an instance of an abstract
class.
What is a Sealed Class?
A sealed class is a class that cannot be inherited from. That means if we have a class
called Customer that is marked as sealed. No other class can inherit from the Customer
class.
What is the abstract method?
A method that does not have the body is called an abstract method. It is declared with the
modifier abstract. It contains only the Declaration/signature and does not contain the
implementation/ body of the method. An abstract function should be terminated with a
semicolon. Overriding of an abstract function is compulsory.
When to use the abstract method?
Abstract methods are usually declared where two or more subclasses are expected to
fulfill a similar role in different ways.
Can a sealed class be used as a base class?
No, the sealed class cannot be used as a base class. A compile-time error will be
generated.
Can an abstract class have a constructor? If so what is the use?
Yes, an abstract class can have a constructor. In general, a class constructor is used to
initialize fields. Along the same lines, an abstract class constructor is used to initialize
fields of the abstract class. We would provide a constructor for an abstract class if we want
to initialize certain fields of the abstract class before the instantiation of a child-class takes
place. An abstract class constructor can also be used to execute code that is relevant for
every child’s class. This prevents duplicate code.
We cannot create an instance of an abstract class. So, what is the use of a
constructor in an abstract class?
Though we cannot create an instance of an abstract class, we can create instances of the
classes that are derived from the abstract class. So, when an instance of a derived class
is created, the parent abstract class constructor is automatically called.
Note: Abstract classes can’t be directly instantiated. The abstract class constructor gets
executed through a derived class. So, it is a good practice to use a protected access
modifier with the abstract class constructor. Using public doesn’t make sense.
An abstract method in an abstract class does not have any implementation, so what
is the use of calling it from the abstract class constructor?
If we want the abstract method to be invoked automatically whenever an instance of the
class that is derived from the abstract class is created, then we would call it in the
constructor of the abstract class.
When should a class be declared as abstract?
A class should be declared as abstract
1. When If it has any abstract methods
2. If it does not provide implementation to any of the abstract methods it
inherited
3. When it does not provide implementation to any of the methods of an
interface
When should a method be declared as sealed in C#?
If we don’t want to allow subclasses to override the superclass method and to ensure that
all sub-classes use the same superclass method logic then that method should be
declared as sealed.
The sealed method cannot be overridden in sub-classes violation leads to a Compile-time
error:
What is the difference between the private and sealed method in C#?
The private method is not inherited whereas the sealed method is inherited but cannot be
overridden. So private method cannot be called from sub-classes whereas the sealed
method can be called from sub-classes. The same private method can be defined in sub-
class and it does not lead to Compile-time error.
When should a class be declared as sealed?
In the below situations we must define the class as sealed
1. If we don’t want to override all the methods of our class in sub-classes.
2. If we don’t want to extend our class functionality.
What are the differences between an abstract class and a sealed class
in C#?

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.

5. An abstract class can contain sealed methods.


6. The abstract method or class cannot be declared as sealed.
7. A subclass of an abstract class can only be instantiated if it implements all
of the abstract methods of its superclass. Such classes are called concrete
classes to differentiate them from abstract classes.
Why can the abstract class not be instantiated?
Because it is not fully implemented in the class as its abstract methods cannot be
executed. If the compiler allows us to create the object for the abstract class, then we can
invoke the abstract method using that object which cannot be executed by CLR at runtime.
Hence to restrict calling abstract methods, the compiler does not allow us to instantiate an
abstract class.
Who will provide the implementation (body) for abstract methods?
Sub-class developers provide the body for abstract methods according to their business
requirements. Basically, in projects, abstract methods (method prototype) are defined by
the superclass developer and they are implemented by sub-class developers.
What type of members can we define in an abstract class?
We can define all static and non-static members including properties, fields, indexes, and
also abstract methods.
Will abstract class members are created when a subclass object is
created?
Yes, its non-static members get memory when its concrete sub-class object is created.
How can we execute static and non-static concrete members of the
abstract class?
Static members can be executed directly from its main method and its non-static members
are executed by using its concrete sub-class object.
Can we declare the abstract method as static?
No, we are not allowed to declare the abstract method as static. It leads to CE: the illegal
combination of modifier abstract and static. If the compiler allows us to declare it as static,
it can be invoked directly which cannot be executed by CLR at runtime. Hence to restrict
in calling abstract methods compiler does not allow us to declare the abstract method as
static.
Can we declare the concrete class as abstract?
Yes, it is allowed. Defining a class as abstract is a way of preventing someone from
instantiating a class that is supposed to be extended first. To ensure our class non-static
members are only accessible via sub-class object we should declare the concrete class
as abstract.
Explain the differences between overriding methods and abstract
methods in C#?
The concept of the abstract method is similar to the concept of method overriding because
in method overriding if a Parent class contains any virtual methods in it, then those
methods can be re-implemented under the child class by using the override modifier.
In a similar way, if a parent class contains any abstract methods in it, those abstract
methods must be implemented under the child class by using the same override modifier.
The main difference between method overriding and abstract method is in the case of
method overriding the child class re-implementing the method is optional but in the case
of the abstract method, the child class implementing the method is mandatory.
What is the need for abstract classes in application development?
The concepts of abstract methods and abstract classes are an extension to the inheritance
wherein inheritance we have been discussing that with the help of a parent class we can
provide property to the child class that can be consumed by the child classes which gives
us re-usability.
Along with the parent providing property to the children, the parent can also impose the
restriction on the children with the help of abstract methods so that all the child classes
have to full fill the restriction without failing.
Polymorphism Interview Questions and Answers in
C#
In this article, I am going to discuss the most frequently asked Polymorphism Interview
Questions and Answers in C#. Please read our previous article where we discussed the
most frequently asked Abstract and Sealed Class Interview Questions in C# with
Answers. As part of this article, we are going to discuss the following Polymorphism
Interview Questions in C# with Answers.
Advertisements

1. What is Polymorphism in C#?


2. Explain the different types of Polymorphism in C#?
3. What is compile-time Polymorphism in C#?
4. What is Runtime Polymorphism in C#?
5. Explain different types of Overloading in C#?
6. What is function overloading?
7. When should we overload methods in C#?
8. What are the advantages of using overloading OR what are the
disadvantages if we define methods with a different name?
9. When is a method considered as an overloaded method?
10. Can we overload methods in the same class?
11. What is the execution control flow of overloaded methods?
12. What is inheritance based overloading?
13. What is the function/method overriding?
14. When must a method be overridden?
15. When is a sub-class method treated as an overriding method?
16. How can we override a parent class method under child class?
17. How can we execute the superclass method if it is overridden in the
sub-class?
18. What is the difference between function overloading and function
overriding?
19. What is method hiding?
20. What is the difference between Method Overriding and Method Hiding?
21. When can a derived class override a base class member?
22. What is the difference between a virtual method and an abstract
method?
23. What is the difference between a virtual method and an abstract
method?
What is Polymorphism in C#?
Polymorphism is one of the primary pillars of object-oriented programming. It allows us to
invoke derived class methods through a base class reference variable during runtime.
In the base class, the method is declared as virtual, and in the derived class, we override
the same method. The virtual keyword indicates that the method can be overridden in any
derived class.
The word Polymorphism is derived from the Greek word, where Poly means many, and
morph means faces/ behaviors. So polymorphism means the ability to take more than one
form.
The same function/ operator will show different behaviors when passed different types of
values or the different number of values. So in simple words, we can say that behaving in
different ways depending upon the input received is known as polymorphism i.e. whenever
the input changes automatically the output or the behavior also changes.
Advertisements

We can implement polymorphism in our application using three


different approaches like
1. Overloading
2. Overriding
3. Hiding
Overloading again is of three types
1. Method overloading
2. Operator overloading
3. Constructor overloading
Explain the different types of Polymorphism in C#?
There are two types of polymorphism
1. Static polymorphism/compile-time polymorphism /early binding
2. Dynamic polymorphism / Run-time polymorphism /late binding
What is compile-time Polymorphism in C#?
This is one of the frequently asked C# Polymorphism interview questions. In the case
of compile-time polymorphism, the object of the class recognizes which method to be
executed for a particular method call at the time of program compilation and binds the
method call with method definition.
This happens in the case of overloading because in the case of overloading each method
will have a different signature and basing on the method call we can easily recognize the
method which matches the method signature. It is also called static polymorphism or
early binding. Static polymorphism is achieved by using function overloading and operator
overloading
What is Runtime Polymorphism in C#?
This is also one of the frequently asked Polymorphism interview questions in C#. In the
case of runtime polymorphism for a given method call, we can recognize which method
has to be executed exactly at runtime but not in compilation time because in the case of
overriding and hiding we have multiple methods with the same signature. So which
method to be given preference and executed that is identified at runtime and binds the
method call with its suitable method. It is also called dynamic polymorphism or late
binding. Dynamic polymorphism is achieved by using function overriding.
Explain different types of Overloading in C#?
Again overloading is classified into three types, such as
1. Method overloading / Function overloading
2. Constructor overloading
3. Operator overloading.
What is function overloading in C#?
Function overloading and method overloading terms are used interchangeably. Method
overloading allows a class to have multiple methods with the same name but with a
different signature. So in C# functions can be overloaded based on the number, type (int,
float, etc), and kind (Value, Ref or Out) of parameters.
The signature of a method consists of the name of the method and the type, kind (value,
reference, or output), and the number of its formal parameters. The signature of a method
does not include the return type and the params modifiers. So it is not possible to overload
a method just based on the return type and params modifier.
A function overloading can be compared with person overloading. If a person has already
some work to do and if we are assigning additional work to the person then the person will
be overloaded.
In the same way, a function will have already some work to do and if we assign different
work to the same function, then we say the function is overloaded. It is an approach of
defining multiple methods with the same method name by changing the
signature. Changing the signature means we can either change the no of parameters
being passed to the method or type of parameters being passed to the method or order
of parameters being passed to the function.
When should we overload methods?
To execute the same logic with different types of arguments we should overload
methods. For example to add two integers, two floats and two strings we should define
three methods with the same name as shown in the below application
What are the advantages of using overloading OR what are the
disadvantages if we define methods with a different name?
If we overload the method, the user of our application gets comfort feeling in using the
method with the impression that he/she calling one method bypassing different types of
values.
The best example for us is the “WriteLine()” method. It is an overloaded method, not a
single method of taking different types of values.
When is a method considered as an overloaded method?
If two methods have the same method name those methods are considered overloaded
methods.
Then the rule we should check is both methods must have different parameter
types/list/order. But there is no rule on return type, non-accessibility modifier and
accessibility modifier means overloading methods can have their own return type, non-
accessibility modifier, and accessibility modifier because overloading methods are
different methods
Can we overload methods in the same class?
Yes, it is possible no CE, no RE. Methods can be overloaded in the same or in super and
subclasses because overloaded methods are different methods.
But we can’t override the method in the same class it leads to CE: “method is already
defined” because overriding methods are the same methods with a different
implementation.
What is the execution control flow of overloaded methods?
The compiler always checks for the called method definition in reference variable type
class with the given argument type parameter. So in searching and executing a method
definition, we must consider both reference variable type and argument type. Referenced
variable type for deciding from which class method should be to bind. Argument type for
deciding which overloaded method should be a bind. For example:
B b = new B();
A a = new B();
b.m1(50) => b.m1(int); In this method call we should search m1() method definition in B
class with integer parameter at the time of program compilation and bind that method
definition.
a.m1(50); => a.m1(int); In this method call we should search m1() method defined in class
A with int parameter not in class B even though the object is B.
What is inheritance based overloading?
A method that is defined in a class can be overloaded under its child class if we overload
a method in this process we call it inheritance-based overloading.
What is the function/method overriding?
Redefining the superclass non-static method in the subclass with the same prototype is
called method overriding. The overriding method is always executed from the class of
the current object.
In object-oriented programming method overriding is a language feature that allows a
subclass to provide a specific implementation of a method that is already provided by one
of its superclasses.
The implementation of the subclass overrides (replaces) the implementation of superclass
methods. So the overridden method is always executed from the object whose object is
stored in the reference variable. The superclass method is called the overridden method
and the sub-class method is called the overriding method.
When must a method be overridden?
If superclass method logic is not fulfilling sub-class business requirements, the subclass
should override that method with the required business logic. Usually, superclass methods
are defined with generic logic which is common for all sub-classes.
When is a sub-class method treated as an overriding method?
If a method in sub-class contains the same signature as the superclass non-private
method then the subclass method is treated as the overriding method and the superclass
method is treated as the overridden method.
How can we override a parent class method under child class?
If we want to override a parent class method in its child class, first the method in the parent
class must be declared as virtual by using the keyword virtual then only the child classes
get the permission for overriding that method. Declaring the method as virtual is marking
the method is overridable.
If the child class wants to override the parent class virtual method then the child class can
do it with the help of the override modifier. But overriding the method under child class is
not mandatory for the child classes. The Syntax is given below:
Class1:
Public virtual void show() //virtual function (overridable)
Class2: Class1
Public override void show() //overriding
Even if the method declared as virtual the child class may or may not override the method
In overriding, the parent class defines a method as virtual and gives it to the child class to
consume that method. So the child class now consumes the method as it is or overrides
that method as per the requirement of the child class. So overriding the parent class virtual
method under a child class is only optional.
How can we execute the superclass method if it is overridden in the
sub-class?
After re-implementing parent class methods under child class, the object of the child class
calls its own methods but not its parent class method, whereas if we want to still consume
or call the parent class’s methods from child class, it can be done in two different ways.
By creating a parent class object under the child class, we can call the parent class
methods from the child class. Or by using the base keyword, we can call parent class
methods from child class, but this and base keyword cannot be used under the static
block.
What is the difference between function overloading and function
overriding?
What is method hiding?
Use the new keyword to hide a base class member. We will get a compile warning if we
miss the new keyword. This is also used for re-implementing a parent class method under
child class. Reimplementing parent class methods under child classes can be done using
two different approaches, such as
1. Method overriding
2. Method hiding
In the first case, we re-implement the parent class methods under child classes with the
permission of the parent class because here in parent class the method is declared as
virtual giving the permission to child classes for overriding the methods.
In the 2nd approach, we re-implement the method of parent class even if those methods
are not declared as virtual that is without parent permission we are re-implementing the
methods. The Syntax is given below.
Class1:
Public void display()
Class2 : Class1
Public new void display()
Using the new keyword for re-implementing the methods in the child class is optional and
if used will give information to hiding.
What is the difference between Method Overriding and Method Hiding?
This is one of the frequently asked Polymorphism interview questions in C#. A parent
class method can be redefined under its child class using two different approaches.
1. Method Overriding.
2. Method Hiding.
In Method overriding, the parent class gives permission for its child class to override the
method by declaring it as virtual. Now the child class can override the method using
the Override keyword as it got permission from the parent. The parent class methods can
be redefined under child classes even if they were not declared as Virtual by using
the ‘new’ keyword.
In method overriding a base class reference variable pointing to a child class object will
invoke the overridden method in the child class. In method hiding a base class reference
variable pointing to a child class object will invoke the hidden method in the base class.
For hiding the base class method from the derived class simply declare the derived class
method with the new keyword. Whereas in C#, for overriding the base class method in a
derived class, we need to declare the base class method as virtual and the derived class
method as the override.
If a method is simply hidden then the implementation to call is based on the compile-time
type of the argument “this”. Whereas if a method is overridden then the implementation to
be called is based on the run-time type of the argument “this”. New is reference-type
specific, overriding is object-type specific.
When can a derived class override a base class member?
A derived class can override a base class member only if the base class member is
declared as virtual or abstract.
What is the difference between a virtual method and an abstract
method?
A virtual method must have a body whereas an abstract method should not have a body.
Can fields inside a class be virtual?
No, Fields inside a class cannot be virtual. Only methods, properties, events, and indexers
can be virtual.
Can you access a hidden base class method in the derived class?
Yes, Hidden base class methods can be accessed from the derived class by casting the
instance of the derived class to an instance of the base class as shown in the example
below.
public class BaseClass

public virtual void Method()

Console.WriteLine("I am a base class method.");

}
}

public class DerivedClass : BaseClass

public new void Method()

Console.WriteLine("I am a child class method.");

public static void Main()

DerivedClass DC = new DerivedClass();

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

1. What is a Delegate in C#? Explain with one example.


2. Types of Delegates in C#.
3. What is Single Cast Delegate in C#
4. What is Multicast Delegate in C#? Explain with one example.
5. Where do you use multicast delegates?
6. Where did you use delegates in your project?
What is a Delegate in C#? Explain with one example.
We can call a method that is defined in a class in two ways
Using Object: We can call the method using the object of the class if it is a non-static
method or we can call the method through class name if it is a static method.
Using Class Name: We can call a method by using a delegate also. Calling a method
using delegate will be faster in execution compared to the first process.
A delegate is also a user-defined type and before invoking a method using delegate we
must have to define that delegate first. A delegate is a type-safe function pointer that
means a delegate holds the reference of a method and then calls the method for
execution.
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

Types of Delegates in C#:


Delegates are classified into two types such as
1. Single cast delegate
2. Multicast delegate
If a delegate is used for invoking a single method then it is called a single cast delegate
or unicast delegate. OR the delegates that represent only a single function is known as a
single cast delegate.
If a delegate is used for invoking multiple methods then it is known as the multicast
delegate. OR the delegates that represent more than one function are called Multicast
delegate.
Note: If we want to call multiple methods using a single delegate the I/O parameters of all
those methods must be the same.
Tip to remember delegate syntax:
Delegates syntax look very much similar to a method with a delegate keyword.
Sample Delegate Program:

What is Multicast Delegate in C#? Explain with one example.


A Multicast delegate is a delegate that has references to more than one function. When
we invoke a multicast delegate, all the functions are invoked that the delegate is pointing
to. There are 2 approaches to create a multicast delegate.
Approach1:
namespace Sample

public delegate void SampleDelegate();

public class Sample

static void Main()

SampleDelegate del1 = new SampleDelegate(SampleMethodOne);

SampleDelegate del2 = new SampleDelegate(SampleMethodTwo);

SampleDelegate del3 = new SampleDelegate(SampleMethodThree);

// In this example del4 is a multicast delegate. We use +(plus)

// operator to chain delegates together and -(minus) operator to remove.

SampleDelegate del4 = del1 + del2 + del3 - del2;

del4();

public static void SampleMethodOne()

Console.WriteLine("SampleMethodOne Invoked");

public static void SampleMethodTwo()

Console.WriteLine("SampleMethodTwo Invoked");

public static void SampleMethodThree()

{
Console.WriteLine("SampleMethodThree Invoked");

}
Approach2:
namespace Sample

public delegate void SampleDelegate();

public class Sample

static void Main()

// In this example del is a multicast delegate. You use += operator

// to chain delegates together and -= operator to remove.

SampleDelegate del = new SampleDelegate(SampleMethodOne);

del += SampleMethodTwo;

del += SampleMethodThree;

del -= SampleMethodTwo;

del();

public static void SampleMethodOne()

Console.WriteLine("SampleMethodOne Invoked");

public static void SampleMethodTwo()

{
Console.WriteLine("SampleMethodTwo Invoked");

public static void SampleMethodThree()

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

public int ID { get; set; }

public string Name { get; set; }

public int Experience { get; set; }

public int Salary { get; set; }

}
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

public delegate bool EligibleToPromotion(Employee EmployeeToPromotion);

public class Employee

public int ID { get; set; }

public string Name { get; set; }

public int Experience { get; set; }

public int Salary { get; set; }

public static void PromoteEmployee(List<Employee> lstEmployees,


EligibleToPromotion IsEmployeeEligible)

foreach (Employee employee in lstEmployees)

if (IsEmployeeEligible(employee))

Console.WriteLine("Employee {0} Promoted", employee.Name);


}

}
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

public class Employee

public int ID { get; set; }

public string Name { get; set; }

public int Experience { get; set; }

public int Salary { get; set; }

public static void PromoteEmployee(List<Employee> lstEmployees,


EligibleToPromotion IsEmployeeEligible)

foreach (Employee employee in lstEmployees)

if (IsEmployeeEligible(employee))

Console.WriteLine("Employee {0} Promoted", employee.Name);


}

class Program

static void Main()

Employee emp1 = new Employee()

ID = 101,

Name = "Pranaya",

Experience = 5,

Salary = 10000

};

Employee emp2 = new Employee()

ID = 102,

Name = "Kumar",

Experience = 10,

Salary = 20000

};

Employee emp3 = new Employee()

ID = 103,
Name = "Rout",

Experience = 20,

Salary = 30000

};

List<Employee> lstEmployess = new List<Employee>();

lstEmployess.Add(emp1);

lstEmployess.Add(emp2);

lstEmployess.Add(emp3);

EligibleToPromotion eligibleTopromote = new


EligibleToPromotion(Program.Promote);

Employee.PromoteEmployee(lstEmployess, eligibleTopromote);

Console.ReadKey();

public static bool Promote(Employee employee)

if (employee.Salary > 10000)

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

static void Main()

Employee emp1 = new Employee()

ID = 101,

Name = "Pranaya",

Experience = 5,

Salary = 10000

};

Employee emp2 = new Employee()

ID = 102,

Name = "Kumar",

Experience = 10,

Salary = 20000

};

Employee emp3 = new Employee()

ID = 103,
Name = "Rout",

Experience = 20,

Salary = 30000

};

List<Employee> lstEmployess = new List<Employee>();

lstEmployess.Add(emp1);

lstEmployess.Add(emp2);

lstEmployess.Add(emp3);

Employee.PromoteEmployee(lstEmployess, x => x.Experience > 5);

Constructor Interview Questions and Answers in C#


In this article, I am going to discuss the most frequently asked Constructor Interview
Questions and Answers in C#. Please read our previous article where we discussed the
most frequently asked Partial Class Interview Questions and Answers in C#. As part
of this article, we are going to discuss the following Constructor Interview Questions in C#
with Answers.
Advertisements

1. What is a Constructor in C#?


2. Can we define a method with the same class name in C#?
3. How many types of constructors are there in C#.net?
4. Explain the Default constructor?
5. Explain the system-defined default constructor?
6. When must the developer provide the constructor explicitly?
7. Explain user-defined default constructor?
8. When should we define the parameterized constructor in a class?
9. Explain about parameterized constructor?
10. How many constructors can be defined in a class?
11. What is a copy constructor in C#?
12. Explain the static constructor in C#?
13. Can we initialize non-static data fields within the static constructor?
14. Can we initialize static data fields within the non-static constructor?
15. Can we initialize static data fields in both static and non-static
constructor?
16. Explain Private constructor in C#?
17. When is a destructor method called?
18. When will be the object of a class gets destroyed?
19. In C# what will happen if you do not explicitly provide a constructor for
a class?
20. Structs are not referenced types. Can structs have constructors?
21. We cannot create instances of static classes. Can we have constructors
for static classes?
22. Can you prevent a class from being instantiated?
23. Can a class or a struct have multiple constructors?
24. Can a child class call the constructor of a base class?
25. If a child class instance is created, which class constructor is called
first – base class or child class?
26. Can a class have a static constructor in C#?
27. Can you mark a static constructor with access modifiers?
28. Can you have parameters for static constructors?
29. What happens if a static constructor throws an exception?
30. Give 2 scenarios where static constructors can be used?
31. What is Destructor?
32. Can a class have more than 1 destructor?
33. Can structs in C# have destructors?
34. Can you pass parameters to destructors?
35. Can you explicitly call a destructor?
36. Why is it not a good idea to use Empty destructors?
37. What is a Constructor in C#?
38. Is it possible to force the garbage collector to run?
39. 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?
40. When do we generally use destructors to release resources?
41. When to use a Private constructor in c#?
What is a Constructor in C#?
Constructors are the special types of methods of a class that get executed when its object
is created. The Constructors in C# are responsible for object initialization and memory
allocation of its class and the new keyword role is creating the object.
Points to Remember.
1. The constructor name should be the same as the class name.
2. It should not contain return type even void also.
3. It should not contain modifiers.
4. In its logic return statement with value is not allowed.
Note:
1. It can have all five accessibility modifiers.
2. The Constructor can have parameters.
3. It can have throws clause it means we can throw an exception from a
constructor.
4. The Constructor can have logic, as part of logic it can have all C#.NET
legal statements except return statement with value.
5. We can place the return; in a constructor.
Can we define a method with the same class name in C#?
No, it is not allowed to define a method with the same class name. It will give a compile-
time error.
How many types of constructors are there in C#.net?
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor
Explain about Default constructor?
Constructor without parameter is called as default constructor. Again default constructor
is classified into two types.
1. System-defined default constructor
2. User-defined default constructor
Explain the system-defined default constructor?
If as a programmer we are not defined any constructor explicitly then the system will
provide one constructor at the time of compilation and that constructor is called a system-
defined default constructor and that constructor will assign default values to the data fields
(non-static variables).
As this constructor is created by the system this is also called a system-defined default
constructor. The system will provide the default constructor only if as a programmer we
are not defined any constructor explicitly.
When must the developer provide the constructor explicitly?
If we want to execute some logic at the time of object creation, that logic may be object
initialization logic or some other useful logic, the developer must provide the constructor
explicitly.
Explain user-defined default constructor?
The constructor which is defined by the developer without any parameter is called a user-
defined default constructor. This constructor does not accept any argument but we can
write the logic in its body.
The drawback of the default constructor is every instance (object) of the class will be
initialized with the same values and it is not possible to initialize each instance of the class
to different values.
When should we define the parameterized constructor in a class?
If we want to initialize objects dynamically with the user given values then we should define
the parameterized constructor.
Explain about parameterized constructor?
The developer given constructor with parameters is called the parameterized
constructor. The advantage of a parameterized constructor is we can initialize each
instance of the class with different values. That means using a parameterized constructor
we can store a different set of values into different objects created to the class.
How many constructors can be defined in a class?
In a class, we can define multiple constructors but every constructor must have a different
parameters type and parameter order. So in a class, we can define one no-argument
constructor plus ‘n’ number of parameterized constructors.
What is a copy constructor in C#?
The constructor takes a parameter of class type is called the copy constructor and this
constructor is used to copy one object data into another object. The main purpose of the
copy constructor is to initialize a new object (instance) with the values of an existing object
(instance).
That means this constructor is used to copy the data of an existing object into a newly
created object that’s why this constructor is called the copy constructor.
Explain the static constructor in C#?
This is one of the frequently asked Constructor Interview Questions in C#.
We can create a constructor as static and when a constructor is created as static, it will
be invoked only once. There is no matter how many numbers of instances (objects) of the
class are created but it is going too invoked only once and that is during the creation of
the first instance (object) of the class.
The static constructor is used to initialize static fields of the class and we can also write
some code inside the static constructor that needs to be executed only once.
Static data fields are created only once in a class even though we are created any number
of objects.
1. There can be only one static constructor in a class.
2. The static constructor should be without any parameter.
3. It can only access the static members of the class.
4. There should not be any access modifier in the static constructor definition.
5. If a class is static then we cannot create the object for the static class.
6. Static constructor will be invoked only once i.e. at the time of first object
creation of the class, from 2nd object creation onwards static constructor will
not be called.
Can we initialize non-static data fields within the static constructor?
It is not possible to initialize non-static data fields within the static constructor, it raises a
compilation error.
Can we initialize static data fields within the non-static constructor?
Yes, we can initialize static data fields within a non-static constructor but after then they
lose their static nature.
Can we initialize static data fields in both static and non-static
constructor?
Yes, we can initialize static data fields in both static and non-static constructors but static
data fields lose their static nature.
Explain Private constructor in C#?
This is one of the frequently asked Constructor Interview Questions in C#. We can also
create a constructor as private. The constructor whose accessibility is private is known as
the private constructor. When a class contains a private constructor then we cannot create
an object for the class outside of the class. Private constructors are used to creating an
object for the class within the same class. Generally, private constructors are used in the
Remoting concept.
When is a destructor method called?
A destructor method gets called when the object of the class is destroyed.
When will be the object of a class gets destroyed?
This is one of the frequently asked Constructor Interview Questions and Answers in
C#. The object of a class will be destroyed by the garbage collector in any of the following
cases
Case1: At the end of a program execution each and every object that is associated with
the program will be destroyed by the garbage collector.
Case2: The Implicit calling of the garbage collector occurs sometime in the middle of the
program execution provided the memory is full so that the garbage collector will identify
unused objects of the program and destroys them.
Case3: The Explicit calling of the garbage collector can be done in the middle of program
execution with the help of the “GC.Collect()” statement so that if there are any unused
objects associated with the program will be destroyed in the middle of the program
execution by the garbage collector.
In C# what will happen if you do not explicitly provide a constructor
for a class?
If you do not provide a constructor explicitly for your class, C# will create one by default
that instantiates the object and sets all the member variables to their default values.
Structs are not referenced types. Can structs have constructors?
Yes, even though Structs are not referenced types, structs can have constructors.
We cannot create instances of static classes. Can we have
constructors for static classes?
Yes, static classes can also have constructors.
Can you prevent a class from being instantiated?
Yes, a class can be prevented from being instantiated by using a private constructor.
Can a class or a struct have multiple constructors?
Yes, a class or a struct can have multiple constructors. Constructors in C# can be
overloaded.
Can a child class call the constructor of a base class?
Yes, a child class can call the constructor of a base class by using the base keyword as
shown in the example below.

If a child class instance is created, which class constructor is called


first – base class or child class?
When an instance of a child class is created, the base class constructor is called before
the child class constructor. An example is shown below.
Can a class have a static constructor in C#?
Yes, a class can have a static constructor. Static constructors are called automatically,
immediately before any static fields are accessed, and are generally used to initialize static
class members. It is called automatically before the first instance is created or any static
members are referenced. Static constructors are called before instance constructors. An
example is shown below.

Can you mark a static constructor with access modifiers?


No, we cannot use access modifiers on the static constructor.
Can you have parameters for static constructors?
No, static constructors cannot have parameters.
What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time,
and the type will remain uninitialized for the lifetime of the application domain in which
your program is running.
Give 2 scenarios where static constructors can be used?
A typical use of static constructors is when the class is using a log file and the constructor
is used to write entries to this file. Static constructors are also useful when creating
wrapper classes for unmanaged code when the constructor can call the LoadLibrary
method.
Advertisements

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

1. Explain different types of errors in C#.


2. What is a Compilation Error and Runtime Error in C#?
3. What is an Exception?
4. Who is responsible for abnormal termination of the program whenever
runtime errors occur?
5. What happens if an exception is raised in the program?
6. What CLR does when a logical mistake occurred in the program?
7. Explain Exception Handling?
8. Why we need exception handling?
9. What is the Exception Handling Procedure?
10. How can we handle the exception in .NET?
11. Explain the difference between Error and Exception in C#?
12. What is the difference between System exceptions and Application
exceptions?
13. Explain about try-catch implementation.
14. Explain the Different Properties of the Exception class in C#.
15. Can we catch all exceptions using a single catch block?
16. When should we write multiple catch blocks for a single try block?
17. Explain about the finally block
18. Why we need finally block in the real-time project?
19. How many ways we can use try-catch and finally?
20. What happens if the finally block throws an exception?
21. What is the difference between the “throw” and “throw ex” in .NET?
22. What is Inner Exception?
Explain different types of errors in C#.
When we write and execute our code in the .NET framework then there is possible of three
types of error occurrences they are
1. Compilation errors
2. Runtime errors
What is a Compilation Error in C#?
An error that occurs in a program at the time of compilation is known as the compilation
error. These errors occur due to syntax mistakes under the program.
These errors occur by typing the wrong syntax like missing double quotes and terminators,
typing wrong spelling for keywords, assigning wrong data to a variable, trying to create an
object for abstract class and interface, etc.
That means this error occurs due to the poor understanding of the programming
language. These errors can be identified by the programmer and can be rectified before
the execution of the program only. So these errors do not cause any harm to the program
execution.
What is Runtime Error in C#?
The errors which are occurred at the time of program execution are called as a runtime
error. These errors are like entering wrong data into a variable, trying to open a file for
which there is no permission, trying to connect to the database with wrong user id and
password, the wrong implementation of logic, missing of required resources, etc.
The Runtime errors are dangerous because whenever they occur in the program, the
program terminates abnormally on the same line where the error gets occurred without
executing the next line of code.
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

static void Main(string[] args)

int a = 20;

int b = 10;

int c;

Console.WriteLine("A VALUE = " + a);

Console.WriteLine("B VALUE = " + b);

c = a / b;

Console.WriteLine("C VALUE = " + c);

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;

Console.WriteLine("A VALUE = " + a);

Console.WriteLine("B VALUE = " + b);

c = a / b;

Console.WriteLine("C VALUE = " + c);

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

static void Main(string[] args)

b = int.Parse(Console.ReadLine());

int a, b, c;

Console.WriteLine("ENTER ANY TWO NUBERS");

a = int.Parse(Console.ReadLine());

if (b == 0)

Console.WriteLine("second number should not be zero");

else

c = a / b;

Console.WriteLine("C VALUE = " + c);

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

public static void Main()

Hello();

}
public static void Hello()

try

// Some code

catch

// Some code

finally

Console.WriteLine("This line will be executed");

int result = Convert.ToInt32("TEN");

Console.WriteLine("This line will NOT be executed");

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

// Process and log the exception

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

public static void Main()

try

Hello();

catch (Exception ex)

Console.WriteLine(ex.Message);

public static void Hello()

{
try

// This exception will be lost

throw new Exception("Exception in TRY block");

finally

throw new Exception("Exception in FINALLY block");

}
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

// do some operation that can fail

catch (Exception ex)

// do some local cleanup

throw;

//Throw ex Syntax:

try
{

// do some operation that can fail

catch (Exception ex)

// do some local cleanup

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

public static void Main()

try

try

Console.WriteLine("Enter First Number");

int FN = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter Second Number");

int SN = Convert.ToInt32(Console.ReadLine());

int Result = FN / SN;


Console.WriteLine("Result = {0}", Result);

catch (Exception ex)

string filePath = @"C:\Sample Files\Log.txt";

if (File.Exists(filePath))

StreamWriter sw = new StreamWriter(filePath);

sw.Write(ex.GetType().Name + ex.Message + ex.StackTrace);

sw.Close();

Console.WriteLine("There is a problem! Plese try later");

else

//To retain the original exception pass it as a parameter

//to the constructor, of the current exception

throw new FileNotFoundException(filePath + " Does not Exist", ex);

catch (Exception ex)

//ex.Message will give the current exception message

Console.WriteLine("Current or Outer Exception = " + ex.Message);

//Check if inner exception is not null before accessing Message property


//else, you may get Null Reference Excception

if (ex.InnerException != null)

Console.WriteLine("Inner Exception = ", ex.InnerException.Message);

SQL Server Interview Questions and Answers


In this article, I am going to discuss the most frequently asked SQL Server Interview
Questions and Answers. As part of this article, we are going to discuss the following 60
SQL Server Interview Questions with answers.
Advertisements

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

What is BCP? When does it use?


BulkCopy is a tool used to copy a huge amount of data from tables and views. BCP does
not copy the structures same as source to destination.
How do you load large data to the SQL server database?
BulkCopy is a tool used to copy a huge amount of data from tables. BULK INSERT
command helps to Imports a data file into a database table or view in a user-specified
format.
Can we rewrite subqueries into simple select statements or with joins?
Subqueries can often be re-written to use a standard outer join, resulting in faster
performance. As we may know, an outer join uses the plus sign (+) operator to tell the
database to return all non-matching rows with NULL values. Hence we combine the outer
join with a NULL test in the WHERE clause to reproduce the result set without using a
sub-query.
Can SQL Servers link to other servers like Oracle?
This is one of the most frequently asked SQL Server Interview Questions. SQL Server can
be lined to any server provided it has an OLE-DB provider from Microsoft to allow a link.
E.g. Oracle has an OLE-DB provider for oracle that Microsoft provides to add it as a linked
server to the SQL Server group.
How to copy the tables, schema, and views from one SQL server to
another?
Microsoft SQL Server 2000 Data Transformation Services (DTS) is a set of graphical tools
and programmable objects that lets user extract, transform, and consolidate data from
disparate sources into single or multiple destinations.
What is Data Warehousing?
Subject-oriented, meaning that the data in the database is organized so that all the
data elements relating to the same real-world event or object are linked together;
Time-variant, meaning that the changes to the data in the database are tracked and
recorded so that reports can be produced showing changes over time;
Non-volatile, meaning that data in the database is never over-written or deleted,
once committed, the data is static, read-only, but retained for future reporting;
Integrated, meaning that the database contains data from most or all of an
organization’s operational applications and that this data is made consistent.
Advertisements

What is OLTP (Online Transaction Processing)?


In OLTP – online transaction processing systems relational database design uses the
discipline of data modeling and generally follows the Codd rules of data normalization in
order to ensure absolute data integrity. Using these rules complex information is broken
down into its most simple structures (a table) where all of the individual atomic level
elements relate to each other and satisfy the normalization rules.
What is Data Integrity?
1. Data integrity means the data contained in the database is accurate and
reliable.
2. To provide data integrity, RDBMS provides a set of integrity constraints
that ensures that data entered into the database is accurate, valid, and
consistent.
What are the different levels of data integrity in SQL Server?
1. Entity Integrity (uniquely identify- PK, UQ)
2. Domain Integrity (Follow defined rule- Check
3. Referential integrity (relationships- FK)
4. User-defined integrity
What is Entity integrity?
1. Entity integrity ensures each row in a table is a uniquely identifiable entity.
We can achieve entity integrity in a table by using either PRIMARY KEY or
UNIQUE KEY constraints.
2. In simple words, we can say Entity Integrity ensures that there are no
duplicate rows in a table.
What is Referential integrity?
1. Referential integrity ensures that relationships between tables remain
preserved as data is inserted, deleted, and modified. We can apply
referential integrity using a FOREIGN KEY constraint.
2. In simple words, we can say that Referential integrity ensures that rows
cannot be updated or deleted which are used by other records.
What is Domain Integrity?
1. Domain integrity ensures that the values going to store in a column must
follow some defined rules such as range, type, and format. A database can
enforce these rules by using the CHECK KEY constraint.
2. 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.
What is user-defined integrity?
User-Defined Integrity enforces some specific business rules that do not fall into an entity,
domain, or referential integrity categories. Each of these categories of data integrity can
be enforced by the appropriate constraints.
What is a Constraint in SQL Server?
A constraint is a property that is assigned to a column or set of columns in a table that is
used to enforce data integrity means it ensures that the data is going to store in a table is
valid, consistent, and accurate.
Why do we need Constraints in SQL Server?
1. A constraint is used to restrict the insertion of unwanted data in any
columns.
2. We can create constraints on single or multiple columns of any table.
3. It maintains the data integrity i.e. accurate data or original data of the table.
What are the different types of Constraints available in SQL Server?
SQL Server supports five constraints for maintaining data integrity which are
1. UNIQUE KEY constraint
2. NOT NULL constraint
3. CHECK KEY constraint
4. PRIMARY KEY constraint
5. FOREIGN KEY constraint.
Note: Constraints are imposed on columns of a table.
What is Default Constraint in SQL Server?
1. The default constraint is used to fill the column with a default value that is
defined during the creation of a table if the user does not supply any value
while inserting the data.
2. IDENTITY columns and timestamp columns can’t be associated with a
default constraint.
3. In simple words, we can say that Default constraints enable the SQL
Server to write default value to a column when the user doesn’t specify a
value.
4. A default allows us to specify a constant value, NULL, or the run-time
value of a system function if no known value exists or if the column is
missing in an INSERT statement.
5. Let us see an example for understanding this concept

What is NOT NULL Constraint in SQL Server?


1. If a NOT NULL constraint is imposed on a column then that column will
not allow null values into it.
2. The NOT NULL Constraint is used to avoid NULL values but accepted
duplicate values into a column.
3. It enforces that the column will not accept NULL values. The NOT NULL
constraints are used to enforce domain integrity as the check constraints.
4. A table can contain any number of NOT NULL constraints.
5. We can apply the NOT NULL constraint on any data type column such as
integer, character, money, etc.
Note: When we INSERT a null value into a column on which the NOT NULL constraint is
imposed. The execution of the insert statement is terminated by displaying a user-friendly
message telling the reason for termination and also specifies the database, the table, and
the column where the problem got occurred.
What is a Unique Constraint in SQL Server?
1. If this constraint is imposed on a column then that column will not allow
duplicate values into it.
2. A UNIQUE constraint is used to avoid duplicate values but accepted null
values in a column.
3. IT enforces the uniqueness of the values in a set of columns, so no
duplicate values are entered. The unique key constraints are used to
enforce entity integrity as the primary key constraints.
4. A table can contain any number of UNIQUE constraints.
5. We can apply the UNIQUE constraint on any data type column such as
integer, character, money, etc.
6. The UNIQUE constraint will accept 1 NULL value only.
Note: The unique key constraint is used to make sure that there is no duplicate value in
that column. Both unique key and primary key enforces the uniqueness of the column but
there is one difference between them unique key constraint allows null value but the
primary key does not allow null value.
Advertisements

IMPOSING CONSTRAINT ON TABLE:


We can impose constraints on a table in two different ways
1. Column-level imposing a constraint
2. Table level imposing a constraint
In the first case, we provide the constraint information inside the column only whereas in
the second case we first define all the columns and then we define constraints on the
columns.
Note: We cannot impose NOT NULL constraint in table level. It is possible only for the
rest of the four constraints.
Column Level Imposing a Constraint:
CREATE TABLE CUSTOMER

CID INT CONSTRAINT CUSTID_UNIQUE UNIQUE,

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

CONSTRAINT CUSTID_UNIQUE UNIQUE(CUSTID)

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

BRANCHLOCATION VARCHAR (30),

CONSTRAINT CITY_BC_UNIQUE UNIQUE(CITY, BRANCHCODE)

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

EMP_NAME VARCHAR(30) NOT NULL,

ENTERED_DATE DATETIME NOT NULL CHECK (ENTERED_DATE >=


CURRENT_TIMESTAMP),

DEPT_NO INT CHECK(DEPT_NO > 0 AND DEPT_NO < 100)

)
Check constraints will be useful to limit the range of possible values in a column.
Advertisements

We could create check constraints at two different levels


1. Column-level check constraints are applied only to the column and cannot
reference data in other columns
2. Table-level check constraints can reference any column within a table but
cannot reference columns in other tables
A table can contain any number of check constraints and will apply to any column data
type like integer, character, and decimal, date, etc.
What is the Primary Key Constraint in SQL Server?
1. PRIMARY KEY is the combination of UNIQUE and NOT NULL constraint
which does not allow either NULL or Duplicate values into a column or
columns.
2. Using the primary key we can enforce entity integrity.
3. PRIMARY KEY is also used to make a relationship with the FOREIGN
KEY constraint on the table.
4. A table should contain 1 PRIMARY KEY constraint only which can be
either on a single or multiple columns i.e. composite primary key also
allowed.
5. Every TABLE should have a primary key constraint to uniquely identify
each row and only one primary key constraint can be created for each table.
6. PRIMARY KEY can apply to any data type like integer, character, decimal,
money, etc.
What is a Composite Primary Key in SQL Server?
1. When the primary key constructed with more than 1 column is called a
composite primary key.
2. The maximum number of columns is including in the composite primary
key is 16 columns.
3. The composite primary key we need to define after all columns definition
i.e. at the end of the table definition.
4. In a composite primary key, each column can accept duplicate values but
the duplicate combinations should not be duplicated.
Note: The primary key is also called a candidate key.
What is Foreign Key Constraint in SQL Server?
1. One of the most important concepts in a database is creating a
relationship between database tables.
2. These relationships provide a mechanism for linking data stores in
multiple tables and retrieving them in an efficient manner.
3. In order to create a link between two tables, we must specify a FOREIGN
KEY in one table that references a column in another table.
4. FOREIGN KEY constraints are used for relating or binding two tables
with each other and then verify the existence of one table data in other
tables.
5. A foreign key in one TABLE points to a primary key in another table.
Foreign keys prevent actions that would leave rows with foreign key values
when there are no primary keys with that value. Foreign key constraints are
used to enforce referential integrity.
To impose a FOREIGN KEY Constraint we require the following things
1. We require two tables for binding with each other and those two tables
must have a common column for linking the tables.
2. The common column that is present in both the tables need not have the
same name but their data type must be the same.
3. The common column that is present under the parent table or master table
is known as a reference key column and the reference key column should
not contain duplicate values in it. So we need to impose either UNIQUE or
PRIMARY key constraint on that column.
4. If we impose a primary key constraint on the reference key column that
column will also be the identity column of the table.
5. The common column which is present in the child or detailed table is
known as the FOREIGN key column and we need to impose a FOREIGN
key constraint on the column which refers to the reference key column of
the master table.
How can we provide the default value for a column?
The default, default value for any column is NULL, provided the column is not imposed
with a NOT NULL constraint. At the time of creating the table, we have a chance of giving
our own default value on the column. So that when we insert a record into the table without
specifying a value to that column automatically the default value comes into the picture
and inserted into the column whereas if we provide a value that provided only will be
inserted.
What is SELF REFERENTIAL INTEGRITY?
This is the same as the referential integrity we have learned earlier. In earlier cases, we
are binding one column of a table with another column of another table whereas in self-
referential integrity we bind a column of a table with another column of the same table i.e.
both the foreign key and primary key will be present in one table only.
Steps to view the primary key and foreign key relationship ER
diagram representation.
1. Go to open SQL Server management studio
2. Click on the new query option
3. Go to the query option from the main menu bar
4. Click on design query in the editor option
5. Select primary key and foreign key tables one by one and click on the add
button
6. Click on the close button
What is the difference between a primary key and a unique key?
This is one of the frequently asked SQL Server Interview Questions. Let us understand
the difference between them.
Both primary key and unique key enforces the uniqueness of the column on which they
are defined. But by default primary key creates a unique clustered index on the column
where are unique key creates a unique non-clustered index by default. Another major
difference is that the primary key doesn’t allow NULLs, but the unique key allows one
NULL only.
Advertisements

What is the difference between primary key and foreign key?


This is one of the frequently asked SQL Server Interview Questions. Let us understand
the difference between a primary key and a foreign key.
Primary key:
1. A primary key uniquely identifies a record in the table.
2. Primary Key can’t accept null values and duplicate values by default,
3. The primary key is a clustered index and data in the database table is
physically organized in the sequence of the clustered index.
4. We can have only one Primary key in a table.
Foreign key:
1. A foreign key is a field in the table that is the primary key (or unique key)
in another table.
2. The foreign key can accept null values and duplicate values.
3. A foreign key does not automatically create an index, clustered, or non-
clustered. We can manually create an index on the foreign key.
4. We can have more than one foreign key in a table.
Note: We can’t insert a foreign key column value into the table if the primary key value
not available but the reverse is possible and we can’t delete the primary key value if the
foreign key reference is set into the table but the reverse is possible.
CAN A TABLE HAVE MULTIPLE UNIQUE, FOREIGN, AND/OR PRIMARY
KEYS?
A table can have multiple unique and foreign keys. However, a table can have only one
primary key.
CAN A UNIQUE KEY HAVE NULL VALUES? CAN A PRIMARY KEY
HAVE NULL VALUES?
Unique key columns are allowed to hold a single NULL value. The values in a primary key
column, however, can never be NULL.
CAN A FOREIGN KEY REFERENCE A NON-PRIMARY KEY?
Yes, a foreign key can actually reference a key that is not the primary key of a table. But
a foreign key must reference a unique key.
CAN A FOREIGN KEY CONTAIN NULL VALUES?
Yes, a foreign key can hold NULL values. Because foreign keys can reference unique,
non-primary keys – which can hold NULL values – this means that foreign keys can
themselves hold NULL values as well.
SQL Server Temporary Tables Interview Questions
and Answers
In this article, I will discuss most frequently asked SQL Server Temporary Tables
Interview Questions and Answers. Please read our previous article where we discussed
the most frequently asked SQL Server Interview Questions with answers. As part of this
article, we are going to discuss the following interview questions on SQL Server
Temporary Tables.
Advertisements
1. What are Temporary Tables in SQL Server?
2. Types of Temporary Tables in SQL Server.
3. What is a Local Temporary Table?
4. What are Global Temporary Tables in SQL Server?
5. What are the differences between Local and Global Temporary
Tables?
6. Can you please explain when to use a temp table in SQL Server?
7. Can you create foreign key constraints on temporary tables?
8. Do you have to manually delete temporary tables?
9. In which database, temporary tables get created?
10. How can I check for the existence of a temporary table?
11. How to copy the structure of the temporary table from one table to
another?
12. What is the difference between a Temporary Table and a Table
variable in SQL Server?
What are Temporary tables?
SQL Server provides the concept of the temporary table which helps us in a great way.
These tables can be created at runtime and can do all kinds of operations that one normal
table can do. But, based on the table types, the scope is limited.
Permanent tables get created in the database we specify and remain in the
database permanently until we delete (drop) them. On the other hand, temporary tables
get created in the TempDB database and are automatically deleted, when they are no
longer used.
What are the 2 types of Temporary Tables in SQL Server?
1. Local Temporary Tables
2. Global Temporary Tables
What is a Local Temporary Table?
the Local temp tables are only available to the current connection for the user, and they
are automatically deleted when the user disconnects from instances. The local temporary
table name is stared with hash (“#”) sign.
Creating a Local Temporary table is very similar to creating a permanent table, except that
we prefix the table name with 1 pound (#) symbol. In the example
below #PersonDetails is a local temporary table, with Id and Name columns.
For example:
CREATE TABLE #PersonDetails(Id Int, Name Varchar(50))
Inserting values into Local Temporary Tables
Insert into #PersonDetails values (1,’Mike’)
Insert into #PersonDetails values (2,’John’)
View the Tables data
Select * from #PersonDetails
What are Global Temporary Tables in SQL Server?
Global Temporary tables name starts with a double hash (“##”). Once this table has been
created by a connection, like a permanent table it is then available to any user by any
connection. It can only be deleted once all connections have been closed. To create a
Global temporary table prefix the name of the table with 2 pounds (##) symbols. For
example.
The Global Temporary Tables are visible to all the connections of the SQL Server and are
only destroyed when the last connection referencing the table is closed.
Multiple users across multiple connections can have Local temporary tables with the same
name but Global Temporary Table Names should be unique and if we inspect the name
of the Global Temporary Table in the object explorer there will be no random numbers
suffixed at the end of the table name.
What are the differences between Local and Global Temporary Tables?
1. Local Temp tables are prefixed with a single pound (#) symbol, whereas
global temp tables are prefixed with 2 pounds (##) symbols.
2. SQL Server appends some random numbers at the end of the local temp
table name where this is not done for global temp table names.
3. The Local temporary tables are only visible to that session of the Server
which has created it, whereas Global temporary tables are visible to all the
server sessions.
4. Local temporary tables are automatically dropped; when the session that
created, the temporary tables are closed. Global temporary tables are also
automatically dropped when the session that creates the temporary
tables is closed.
Can you please explain when to use a temp table in SQL Server?
When we want to perform many operations on the data in a specific table in the database,
we can load the data into a temporary table and then we can perform operations on the
temporary table. Loading data into a temporary table speeds up the process because all
the operations are performed locally on the client. Use of the Temporary Tables reduces
the load on both the network and server as all the interaction with temporary tables occurs
on the Client.
1. When we are doing a large number of row manipulation in stored
procedures.
2. This is useful to replace the cursor. We can store the result set data into a
temp table, then we can manipulate the data from there.
3. When we are having a complex join operation.
4. A Temporary Table variable can be very useful when used with stored
procedures to pass input/output parameters or to store the result of a table-
valued function.
Can you create foreign key constraints on temporary tables?
No
Do you have to manually delete temporary tables?
No, temporary tables are automatically dropped, when the session that created the
temporary tables is closed. But if we maintain a persistent connection or if connection
pooling is enabled, then it is better to explicitly drop the temporary tables we have
created. However, it is generally considered a good coding practice to explicitly drop every
temporary table we create.
In which database, the temporary tables get created?
TEMPDB database.
How can I check for the existence of a temporary table?
IF OBJECT_ID('tempdb..#LocalTempTable') IS NOT NULL
Begin
Drop table #LocalTempTable
Print 'Temporary table #LocalTempTable is deleted'
End
Else
Begin
Print 'Temporary table #LocalTempTable is not Found,
it may have been deleted already'
End
Usually, it is best to create a temp table through the create function. For example, if we
want to check if that temp table existed and then drop/create a new one and insert data it
would go something like this.
IF object_ID('tempdb..##temptable') IS NOT NULL
DROP TABLE ##TEMPTABLE
CREATE TABLE ##TEMPTABLE
INSERT INTO ##TEMPTABLE
SELECT e.EMPLOYEE
FROM Employee e
WHERE e.employeename = 'Pranaya'
This would check for the table and drop it if it exists then would create a new global temp
table (indicated by the ##) and insert all employees with the name Pranaya into this temp
table.
SQL appends random function as at the end of the Local table’s name.
So, we can create a Local table with the same name. But the Global
table’s name has to be unique. Why is that?
It is because a Local table is available to the connection that created it. Other users can
have that name for their local table. But in the case of a global temporary table, it is
available to all users on different sessions. So, its name cannot be different.
How to copy the structure of the temporary table from one table to
another? i.e., copying the only structure and no data?
Select * into #Temp1 from tblEmployee
Select Top 0 * into #Temp2 from #Temp1
--Or
Select * into #Temp1 from tblEmployee where 1=2
What is the difference between a Temporary Table and a Table
variable?
1. A table variable is created in the memory whereas a temporary table is
created in the TempDB. But if there is memory pressure, the pages
belonging to a table variable may be pushed out to tempdb.
2. Table variables cannot be involved in transactions, logging or locking. This
makes the table variable faster than a temporary table.
3. We can pass the table variable as a parameter to functions and stored
procedures, whereas we cannot do the same with a temporary table.
4. The temporary table can have indexes, whereas a table variable can only
have a primary index. If speed is an issue Table variable can be faster, but
if there are a lot of records, or there is a need to search the temporary table
based on a clustered index, then a Temporary Table would be better. If we
have less than 100 rows generally use a table variable. Otherwise, use a
temporary table. This is because SQL Server won’t create statistics on table
variables.
Both Temporary Tables (#Tables) and Table Variables (@Tables) in SQL Server
provide a mechanism for Temporary holding/storage of the result-set for further
processing
SQL Server Indexes Interview Questions and
Answers
In this article, I am going to discuss the most frequently asked SQL Server Indexes
Interview Questions and Answers. Please read our previous article where we discussed
the most frequently asked SQL Server Temporary Tables Interview Questions and
Answers. As part of this article, we are going to discuss the following SQL Server Indexes
Interview Questions with answers.
Advertisements

1. How is data stored in a database in SQL Server?


2. How will be the database engine retrieves the information from a table in
SQL Server?
3. What is the use of an Index in SQL Server?
4. What is an Index in SQL Server?
5. Why do we need Indexes in SQL Server?
6. What are the types of Indexes available in SQL Server?
7. What is a Clustered Index in SQL Server?
8. What is a Non-Clustered Index in SQL Server?
9. What is the difference between clustered and non-clustered index?
10. What is a Unique Index?
11. What are the differences between UNIQUE Constraints and the UNIQUE
Index?
12. When should we be creating a unique constraint over a unique index?
13. When SQL Server uses Indexes?
14. When should we create indexes on a table?
15. What is a Covering Query in SQL Server?
16. What is a table scan? Or what is the impact of table scans on
performance?
17. What is the purpose of the query optimizer in SQL Server?
18. What is the first thing you will check for if the query below is performing
very slowly?
19. What is the significance of an Index on the column used in the GROUP
BY clause?
20. What is the role of an Index in maintaining a unique column in a table?
21. What are the disadvantages of an Index in SQL Server?
22. How many Clustered and Non-Clustered Indexes can you have per
table?
23. Which Index is faster, Clustered or Non-Clustered Index?
24. When is it usually better to create a unique non-clustered index on the
primary key column?
25. What is a Composite Index in SQL Server? or What is the advantage of
using a Composite Index in SQL Server? or What is Covering Query?
26. What are the different index configurations a table can have?
27. What is a table called, if it does not have neither Cluster nor Non-
cluster Index? What is it used for?
28. How to know which index a table is using?
How is data stored in a database?
1. SQL Server stores data in it under data pages where a data page is a
memory location for storing the information.
2. A data page will be having a size of 8KB and every 8 data pages we
stored under a logical container known as “extend”.
How will be the database engine retrieves the information from a table?
This is one of the frequently asked SQL Server Indexes Interview Questions. Whenever
the database engine wants to retrieve the information from the table it will adopt two
different mechanisms for searching the data
1. Full page scan
2. Index Scan
In the first case, SQL Server will search for the required information in each and every
data page to collect the information. So, if the tables having more number of rows it will
take lots of time for searching all the data so it is a time-consuming process.
In the second case SQL Server without searching into each and every data page for
retrieving the information it will make use of an index for retrieving the information, where
an index is a pointer to the information what we retrieve which can reduce the disk I/O
operation saving the time, but if we want to use index scan for searching the data first the
index has to be created.

Note: Whenever an index is created on a column or columns of a table internally an index


table gets created maintaining the information of a column on which the index is created
as well as the address (pointer to the row corresponding to a column).
What is the use of an Index in SQL Server?
Relational databases like SQL Server use indexes to find data quickly when a query is
processed. Creating the proper index can drastically increase the performance of an
application.
What is an index?
1. An index is a database object which is used by the SQL server to speed
up the performance of queries by providing query access to rows in the data
table.
2. By using indexes, we can save time and we can improve the performance
of database queries and applications.
3. When we create an index on any column SQL Server internally maintains
a separate table called index table so that when any user trying to retrieve
the data from the existing table depends on index table SQL Server directly
go to the table and retrieve required data very quickly.
4. In a table, we can use a maximum of 250 indexes. The index type refers
to the way the index is stored internally by SQL Server.
Why do we need Indexes in SQL Server?
1. Indexes are used by queries to find data from tables quickly. Indexes are
created on tables and views. Index on a table or a view is very similar to an
index that we find in a book.
2. If we don’t have an index in a book and ask us to locate a specific chapter
in that book, we will have to look at every page starting from the first page
of the book.
3. On, the other hand, if we have the index, we look up the page number of
the chapter in the index, and then directly go to that page number to locate
the chapter.
4. Obviously, the book index is helping to drastically reduce the time it takes
to find the chapter.
5. In a similar way, Table and View indexes can help the query to find data
quickly.
6. In fact, the existence of the right indexes can drastically improve the
performance of the query. If there is no index to help the query, then the
query engine checks every row in the table from the beginning to the end.
This is called a Table Scan. A table scan is bad for performance.
What are the types of Indexes available in SQL Server?
1. Clustered Index
2. Non-Clustered Index
What is a Clustered Index in SQL Server?
1. In the case of a clustered index, the arrangement of the data in the index
table will be the same as the arrangement of the data of the actual table.
2. Example: The index we find the start of a book.
3. When a table has a clustered index then the table is called a clustered table.
4. If a table has no clustered index its data rows are stored in an unordered
structure.’
5. A table can have only one clustered index in it which will be created when
the primary key constraint used in a table.
6. A clustered index determines the physical order of data in a table. For this
reason, a table can have only one clustered index.
What is a Non-Clustered Index in SQL Server?
1. In the case of a non-clustered index, the arrangement of data in the
index table will be different from the arrangement of the actual table.
2. A non-clustered index is analogous to an index in a textbook. The data is
stored in one place, the index is another place. The index will have pointers
to the storage location of the data.
3. Since, the non-clustered index is stored separately from the actual data a
table can have more than one non clustered index, just like how a book can
have an index by chapters at the beginning and another index by common
terms at the end.
4. In the index itself, the data is stored in an ascending or descending order
of the index key which does not in any way influence the storage of data in
the table.
5. In a table, we can create a maximum of 249 non clustered indexes.
What is the difference between clustered and non-clustered index in
SQL Server?
This is one of the frequently asked SQL Server Indexes Interview Questions. Let us
understand the differences.
1. Only one clustered index per table whereas we can have more than one
non-clustered index.
2. Clustered Index is slightly faster than the Non-Clustered Index. This is
because when a Non Clustered Index is used there is an extra look up from
the Non-Clustered Index to the table, to fetch the actual rows.
3. The clustered index determines the storage order of rows in the table and
hence does not require additional disk space whereas a non-clustered
index is stored separately from the table, additional storage space is
required.
4. A clustered index is a special type of index that reorders the way records
in the table are physically stored. Therefore a table can have only one
clustered index.
5. A non-clustered index is a special type of index in which the logical order
of the index does not match the physical stored order of the rows on disk.
What is a Unique Index in SQL Server?
1. If the index is created by using the “UNIQUE” option then that column on
which the index is created will not allow duplicate values i.e. it works as a
unique constraint.
2. The unique constraint can be either unique clustered or unique non-
clustered also.
3. While creating an index if clustered or non-clustered is not specified by
default it is non-clustered.
4. A unique index is used to enforce uniqueness of key values in the index.
What are the differences between UNIQUE Constraints and the UNIQUE
Index?
There are no major differences between a unique constraint and a unique index. In fact,
when we add a unique constraint, a unique index gets created behind the scenes.
ALTER TABLE tblEmployees ADD
CONSTRAINT UQ_tblEmplyees_City UNIQUE (city)
It will create a UNIQUE non clustered index on the City column. If we want we can also
create a clustered unique index on City column like below
ALTER TABLE tblEmployees ADD CONSTRAINT UQ_tblEmplyees_City UNIQUE
CLUSTERED (city)
It will create a clustered index on the City column.
When should we be creating a unique constraint over a unique
index?
To make our intentions clear, create a unique constraint when data integrity is the
objective. This makes the objective of the index very clear. In either case, data is validated
in the same manner, and the query optimizer does not differentiate between a unique
index created by a unique constraint or manually created.
When SQL Server uses Indexes?
1. SQL Server uses indexes of a table provided the select or update or
delete statement contained “WHERE” condition in them and moreover the
where condition column must be an indexed column.
2. If the select statement contains an “ORDER BY” clause also indexes will
use.
NOTE: When SQL Server is searching for information under the database first it verifies
the best execution plan for retrieving the data and uses that plan which can be either a
full-page scan and index scan also.
When should we create indexes on a table?
1. We need to create an index on a table column provided those columns are
frequently used in where condition or order by clause.
2. It is not advised creating an index on each and every column because a
number of indexes can degrade the performance of the database also
because every modification we make on the data should be reflected in all
the index tables.
What is a Covering query?
1. If all the columns that we have requested in the select clause of the query
are present in the index, then there is no need to look up in the table again.
The requested column data can simply be returned from the index.
2. A clustered index always covers a query, since it contains all of the data in
a table. A composite index is an index on two or more columns. Both
clustered and non-clustered indexes can be composite indexes. To a
certain extent, a composite index can cover a query.
What is a table scan? Or what is the impact of table scans on
performance?
This is one of the frequently asked SQL Server Indexes Interview Questions. When SQL
Server has no index to use for searching, the result is similar to the reader who looks at
every page in a book to find a word. The SQL engine needs to visit every row in a table.
In database terminology, we call this behavior a table scan or just scan. A full table scan
of a very large table can degrade the performance. Creating proper indexes will allow the
database to quickly narrow in on the rows to satisfy the query and avoid scanning every
row in the table.
What is the system stored procedure that can be used to list all the
indexes that are created for a specific table?
sp_helpindex is the system stored procedure that can be used to list all the indexes that
are created for a specific table. For example, to list all the indexes on table tblCustomers,
we can use the following command.
EXEC sp_helpindex tblCustomers
What is the purpose of the query optimizer in SQL Server?
An important feature of SQL Server is the query optimizer (component). The query
optimizer’s job is to find the fastest and least resource-intensive means of executing
incoming queries. An important part of this job is selecting the best index or indexes to
perform the task.
What is the first thing you will check for if the query below is performing
very slowly?
SELECT * FROM tblProducts ORDER BY UnitPrice ASC
Check if there is an Index created on the UntiPrice column used in the ORDER BY clause.
An index on the UnitPrice column can help the above query to find data very quickly. When
we ask for sorted data, the database will try to find an index and avoid sorting the results
during the execution of the query. We control sorting of data by specifying a field, or fields,
in an ORDER BY clause, with the sort order as ASC (ascending) or DESC (descending).
With no index, the database will scan the tblProducts table and sort the rows to process
the query. However, if there is an index, it can provide the database with a presorted list
of prices. The database can simply scan the index from the first entry to the last entry and
retrieve the rows in sorted order.
The same index works equally well with the following query, simply by scanning the index
in reverse.
SELECT * FROM tblProducts ORDER BY UnitPrice DESC
What is the significance of an Index on the column used in the GROUP
BY clause?
Creating an Index on the column, that is used in the GROUP BY clause, can greatly
improve the performance. We use a GROUP BY clause to group records and aggregate
values, for example counting the number of products with the same UnitPrice. To process
a query with a GROUP BY clause the database will often sort the results on the columns
included in the GROUP BY.
The following query counts the number of products at each price by grouping together
records with the same UnitPrice value.
SELECT UnitPrice, Count(*) FROM tblProducts GROUP BY UnitPrice
The database can use the index (Index on UNITPRICE column) to retrieve the prices in
order. Since matching prices appear in consecutive index entries, the database is able to
count the number of products at each price quickly. Indexing a field used in a GROUP
BY clause can often speed up a query.
What is the role of an Index in maintaining a unique column in a table?
1. Columns requiring unique values (such as primary key columns) must
have a unique index applied. There are several methods available to create
a unique index.
2. Marking a column as a primary key will automatically create a unique
index on the column.
3. We can also create a unique index by checking the Create UNIQUE
checkbox when creating the index graphically.
4. We can also create a unique index using SQL with the following command:
CREATE UNIQUE INDEX IDX_ProductName On Products (ProductName)
The above SQL command will not allow any duplicate values in the ProductName column
and an index is the best tool for the database to use to enforce this rule. Each time an
application adds or modifies a row in the table, the database needs to search all existing
records to ensure none of the values in the new data duplicate existing values.
What are the disadvantages of an Index in SQL Server?
This is one of the frequently asked SQL Server Indexes Interview Questions. There are 2
disadvantages of an Index
1. Increased Disk Space
2. Insert, Update and Delete statements could be slow. In short, all DML
statements could be slow.
Disk Space: Indexes are stored on the disk and the amount of space required will depend
on the size of the table and the number and types of columns used in the index. Disk
space is generally cheap enough to trade for application performance, particularly when
a database serves a large number of users.
Insert, Update and Delete statements could be slow: Another downside to using an
index is the performance implication on data modification statements. Any time a query
modifies the data in a table (INSERT, UPDATE, or DELETE), the database needs to
update all of the indexes where data has changed. Indexing can help the database during
data modification statements by allowing the database to quickly locate the records to
modify, however, providing too many indexes to update can actually hurt the performance
of data modifications. This leads to a delicate balancing act when tuning the database for
performance.
How many Clustered and Non-Clustered Indexes can you have per
table?
Clustered Index: Only one Clustered Index per table. A clustered index contains all of the
data for a table in the index, sorted by the index key. The Phone Book is an example of
the Clustered Index.
Non-Clustered Index: We can have multiple Non-Clustered Indexes per table. Index at
the back of a book is an example of a Non-Clustered Index.
For SQL Server 2005: 1 Clustered Index + 249 Nonclustered Index = 250 Index
For SQL Server 2008: 1 Clustered Index + 999 Nonclustered Index = 1000 Index
Which Index is faster, Clustered or Non Clustered Index?
Clustered Index is slightly faster than the Non-Clustered Index. This is because when a
Non Clustered Index is used there is an extra look up from the Non-Clustered Index to the
table, to fetch the actual rows.
When is it usually better to create a unique non-clustered index on
the primary key column?
Sometimes it is better to use a unique non-clustered index on the primary key column,
and place the clustered index on a column used by more queries. For example, if the
majority of searches are for the price of a product instead of the primary key of a product,
the clustered index could be more effective if used on the price field.
What is a Composite Index in SQL Server? or What is the advantage of
using a Composite Index in SQL Server? or What is Covering Query?
A composite index is an index on two or more columns. Both clustered and non-clustered
indexes can be composite indexes.
If all of the information for a query can be retrieved from an Index then it is called as
Covering query. A clustered index, if selected for use by the query optimizer, always
covers a query, since it contains all of the data in a table.
What are the different index configurations a table can have?
A table can have one of the following index configurations:
1. No indexes
2. A clustered index
3. A clustered index and many non-clustered indexes
4. A non-clustered index
5. Many non-clustered indexes
What is a table called, if it does not have neither Cluster nor Non-cluster
Index? What is it used for?
Unindexed table or Heap. Microsoft Press Books and Book On Line (BOL) refers to it as
Heap. A heap is a table that does not have a clustered index and, therefore, the pages
are not linked by pointers. The IAM pages are the only structures that link the pages in a
table together.
Unindexed tables are good for fast storing of data. Many times it is better to drop all
indexes from table and than do bulk of inserts and to restore those indexes after that.
How to know which index a table is using?
SELECT table_name,index_name FROM user_constraints
What is a Trigger in SQL Server?
A Trigger is a database object which can also be treated as a special kind of stored
procedure that automatically executes when language events (INSERT, DELETE or
UPDATE) occurs. Triggers are stored in and managed by the DBMS. Triggers are similar
to stored procedures in that both consist of procedural logic that is stored at the database
level.
However, the difference between a trigger and a stored procedure is that the trigger is
attached to a table and is only fired when an INSERT, UPDATE or DELETE operation
occurred whereas stored procedures are not attached to a specific table and can be
executed explicitly by making a call to the stored procedure. In addition to that, triggers
can also execute stored procedures.
Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within
itself; so, when the trigger is fired because of data modification, it can also cause another
data modification, thereby firing another trigger. A trigger that contains data modification
logic within itself which causes another trigger to be fired is called the nested trigger.
What are the types of Triggers available in SQL Server?
The following are the two types of triggers in SQL Server.
1. After Triggers (For Triggers): Fired after Insert, Update and Delete
operations on a table.
2. Instead of Triggers: Fired instead of Insert, Update and Delete
operations on a table.
In SQL Server, there are 4 types of triggers
1. DML Triggers – Data Manipulation Language
2. DDL Triggers – Data Definition Language
3. CLR triggers – Common Language Runtime
4. Logon triggers
What are the special tables used by Triggers in SQL Server?
Triggers make use of two special tables called inserted and deleted. The inserted table
contains the data referenced in an INSERT before it is committed to the database.
The deleted table contains the data in the underlying table referenced in a DELETE
before it is removed from the database. When an UPDATE is issued both tables are used.
More specifically, the new data referenced in the UPDATE statement is contained in the
inserted table and the data that is being updated is contained in the deleted table.
What is MAGIC TABLE in triggers?
These are the special kind of table which is created inside of a trigger when we perform
insert, update and delete operations. The Magic tables are invisible tables or virtual tables.
We can see them only with the help of TRIGGERS in SQL Server. The Magic tables are
those tables that allow us to hold INSERTED, DELETED and UPDATED values during
insert delete and update DML operations on a table in SQL Server.
Basically there are two types of magic tables in SQL Server namely INSERTED and
DELETED magic table. The UPDATE can be performed with the help of these two.
What is the INSERTED Magic Table?
This table is created when we perform an insert operation that provides access to the
values being inserted into the table.
Whenever we insert the values into a table those values we can see in the inserted magic
table like below
CREATE TRIGGER T1 ON EMPLOYEE

FOR INSERT

AS

BEGIN

SELECT * FROM inserted

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

SELECT * FROM deleted

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:

DML triggers can be again classified into 2 types.


1. After trigger (Sometimes called as FOR triggers)
2. Instead of trigger
After triggers as the name says fires after the triggering action. The INSERT,
UPDATE, and DELETE statements cause an after trigger to fire after the respective
statements complete execution.
On the other hand, as the name says, INSTEAD of triggers, fires instead of the
triggering action. The INSERT, UPDATE, and DELETE statements, can cause an
INSTEAD OF trigger to fire INSTEAD OF the respective statement execution.
How to view the updating data in a table?
When we perform an update operation we will be having both inserted and deleted tables
where inserted will provide access to the new values being inserted and deleted table
provides access to the old values of the table.
Whenever we update a record data in the table, we can view the new value in the inserted
magic table and old value in the deleted magic table like below.
CREATE TRIGGER T3 ON EMPLOYEE

FOR UPDATE

AS

BEGIN

SELECT * FROM deleted

SELECt * FROM inserted

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>

ON ALL SERVER/ DATABASE

[with trigger attributes]

FOR / ALTER <Event_Type>

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.

How many types of views are there in SQL Server?


We can create the view in two ways those are
1. Simple view and Updatable views
2. Complex view and non-updatable views.
What is a simple view or Updatable view?
1. The view which is created basing on the columns of a single table is
known as the simple view.
2. We can perform all DML operations on a simple view so that a simple view
is also called an updatable view or dynamic view.
What is a complex View in SQL Server?
1. When we create a view on more than 1 table then it is known as the
complex view.
2. On a complex view, we cannot perform DML operations so that a complex
view is also called a non-updatable or static view.
Can we drop a table that has dependent views on it?
Yes, we can drop a table even if any dependent views are associated with it, but the views
that are associated with it will not be dropped. They will still execute in the database only
with the status as inactive object and all those views become active and start functioning
provided the table is recreated.
Can we create a view based on other views?
Yes, we can create a view based on other views. Usually, we create views based on
tables, but it is also possible to create views based on views.
Can we update the views?
Yes, views can be updated. However, updating a view that is based on multiple tables,
may not update the underlying tables correctly. To correctly update a view that is based
on multiple tables we can make use “Instead OF triggers” in SQL Server.
Why do we need Views in SQL Server?
To protect the data. If we have a table containing sensitive data in certain columns, we
might wish to hide those columns from certain groups of users. For instance, customer
names, addresses, and social security numbers might all be stored in the same table;
however, for lower-level employees like shipping clerks, you can create a view that only
displays customer name and address. You can grant permissions to a view without
allowing users to query the original tables.
A view is a logical table but what it stores internally is a select statement that is used for
creating the view. So that whenever a user performs an operation on the view like select,
insert, update or delete internally the view performs those operations on a table.
Simply we can say that view will act as an interface between the data provider (Table) and
the User.
A view is created based on a table any changes that are performed on the table reflect
into the view any changes performed on the view reflected in the table also.
What are the advantages of using views? OR when do you usually use
views?
Advantages of using views:
Views can be used to reduce the complexity of the database schema, for non-IT users.
The sample view, vWEmployeesByDepartment, hides the complexity of joins. Non-IT
users find it easy to query the view, rather than writing complex joins.
Views can be used as a mechanism to implement row and column level security.
Advertisements
Row Level Security:
For example, I want an end-user, to have access only to IT Department employees. If I
grant him access to the underlying tblEmployees and tblDepartments tables, he will be
able to see, every department employee. To achieve this, I can create a view, which
returns only IT Department employees, and grants the user access to the view and not to
the underlying table.
Column Level Security:
Salary is confidential information and I want to prevent access to that column. To achieve
this, we can create a view, which excludes the Salary column, and then grant the end-
user access to these views rather than the base tables.
Views can be used to present only aggregated data and hide detailed data. The view
that returns summarized data, Total number of employees by Department.
What are indexed views? Or What are materialized views?
A view is a virtual table that means it does not contain any physical data. A view is nothing
more than a compiled SQL query. Every time, we issue a select query against a view, we
actually get the data from the underlying base tables and not from the view, as the view
itself does not contain any data.
When we create an index on a view, the data gets physically stored in the view. So, when
we issue a select query against an indexed view, the data is retrieved from the index
without having to go to the underlying table, which will make the select statement to work
slightly faster. However, the disadvantage is INSERT, UPDATE and DELETE operations
will become a little slow, because every time we insert or delete a row from the underlying
table, the view index needs to be updated. In short, DML operations will have a negative
impact on performance.
Oracle refers to indexed views as materialized views.
Only the views created with schema binding can have an Index. Simply adding WITH
SCHEMABINDING to the end of the CREATE VIEW statement will accomplish this.
However, the effect is that any changes to the underlying tables which will impact the view
are not allowed. Since the indexed view is stored physically, any schema changes would
impact the schema of the stored results set. Therefore, SQL Server requires that schema
binding is used to prevent the view’s schema (and therefore the underlying tables) from
changing.
The first index for a view must be a UNIQUE CLUSTERED INDEX, after which, it’s
possible to create non-clustered indexes against the view.
Indexed Views are heavily used in data warehouses and reporting databases that are not
highly transactional.
What are the limitations of a View?
1. We cannot pass parameters to a view.
2. Rules and Defaults cannot be associated with views.
3. The ORDER BY clause is invalid in views unless TOP or FOR XML is also
specified.
4. Views cannot be based on temporary tables.
SQL Server Joins Interview Questions and Answers
In this article, I am going to discuss the most frequently asked SQL Server Joins
Interview Questions and Answers. Please read our previous article where we discussed
the most frequently asked SQL Server Stored Procedure Interview Questions and
Answers. As part of this article, we are going to discuss the following SQL Server Joins
Interview Questions with answers.
Advertisements
1. What are Joins in SQL Server?
2. Explain the different types of Joins in SQL Server.
3. What are ANSI and NON-ANSI Joins in SQL Server?
4. Explain about EQUI Join in SQL Server
5. Explain about INNER JOIN in SQL Server
6. Explain about OUTER JOIN in SQL Server
7. What is the left outer join?
8. What is the right outer join?
9. What is the full outer join?
10. Explain about CROSS join in SQL Server
11. What is self-join in SQL Server?
12. Differences between UNION and UNION ALL in SQL Server
13. Difference between JOIN and UNION in SQL Server
14. What is a cross join? Explain with an example?
15. What is inner Join in SQL Server? Explain with an example?
16. What is the Left Outer Join in SQL Server? Explain with an
example?
17. What is the Right Outer Join in SQL Server? Explain with an
example?
18. What is Full Outer Join in SQL Server? Explain with an example?
What are Joins in SQL Server?
Joins in SQL Server are used to retrieve data from 2 more related tables. In general, tables
are related to each other using foreign key constraints. An SQL JOIN is used to combine
rows from two or more tables based on a common field between them.
Explain the different types of Joins in SQL Server.
JOINS are classified into two types such as
1. ANSI format JOINS
2. NON-ANSI format JOINS
Again the ANSI format joins classified into three types such as
1. Inner join
2. Outer join
3. Cross join
Further, the outer join divided into three types they are as follows
1. Left outer join
2. Right outer join
3. Full outer join
NON-ANSI format JOINS are classified into four types such as
1. EQUI join
2. NON-EQUI join
3. SELF-join
4. Natural Join
What are the different types of joins available in SQL server?
There are 3 different types of joins available in SQL server, and they are
1. Cross Join
2. Inner Join or Join
3. Outer Join
What are ANSI and NON-ANSI Joins in SQL Server?
When we retrieve the data from multiple tables based on ‘ON’ keyword condition then it is
called ANSI format joins whereas when we retrieve the information from multiple tables
based on ‘WHERE’ keyword condition then it is called as NON-ANSI format joins.
The most important point we need to keep in mind is that when we implement the JOIN
mechanism on the tables then the tables should contain a related column.
When we execute the JOINS on the tables then each record of a table will join with each
record of another table. JOINS are using for retrieving the data purpose only but not
executed purpose. When we get the result from multiple tables, the result is temporary
only but not permanent storage of data.
What is the default JOIN in SQL Server?
The default join of joins is INNER JOIN.
What is the default join of outer join?
The default join of the outer join is a full outer join.
Explain about EQUI Join in SQL Server:
When we retrieve the data from the table based on equality condition then it is known as
EQUI join. (Use equal “=” operator only). It is NON-ANSI format join. Hence when we
make a query for join using an equality operator, then that join query comes under EQUI
join.
Note: Output depends on the table order, not on the query condition.
Explain about INNER JOIN in SQL Server.
Inner join returns only the matching rows between both the tables. Non-matching rows are
eliminated. The inner join is used to retrieve matching data from both the tables. The join
that displays only the rows that have a match in both the joined tables is known as an
inner join.
Explain about OUTER JOIN in SQL Server.
The OUTER JOIN is an extension of INNER JOIN or EQUI JOIN. In an inner join, the user
will get matching data only from the tables i.e. the user will lose un-matching data from
the tables. So to overcome the above problem we use the outer join mechanism.
By using the outer join we can retrieve matching data and also un-matching data from the
tables. Outer join again classified into three types.
1. Left outer join
2. Right outer join
3. Full outer join
What is the left outer join?
It retrieves matching data from both the tables and also un-matching data from the left
side table only. Un-matching data take null value in this case.
What is the right outer join?
It retrieves matching data from both the tables and also un-matching data from the right
side table.
What is the full outer join?
It retrieves matching data and also un-matching data from both tables at a time.
Explain about CROSS join in SQL Server.
If two or more tables are combined with each other without any condition we call it a
Cartesian or cross join. When we join the records without any condition is known as
CROSS JOIN. In cross join, each record of a table is joins with each record of another
table. Cross Join should not have an ON clause.
A cross joins that produces the Cartesian product of the tables that are involved in the
join. The size of a Cartesian product is the number of rows in the first table multiplied by
the number of rows in the second table like this.
Explain about NON-EQUI JOIN in SQL Server.
When we retrieve the information from the tables with any condition except equality
condition then it is known as NON-EQUI JOIN. We may use <, >, <=,>=, <!,>!, AND, OR,
NOT, etc except “=” operator.
What is self-join in SQL Server?
Joining a table by itself is called a self-join. When we have some relation between the
columns within the same table then we use the self-join mechanism. When we implement
a self-join mechanism we should create the alias for the table. We can create any number
of aliases for a single table. Self-join is not a different kind of join. It can be classified of
any type of join
1. Inner Join
2. Outer (Left, Right, full) join
3. Cross Join
Self-join is just like any other join except that two instances of the same table will be joined
in the query. Here is an example: Employees table which contains rows for normal
employees as well as managers of that employee. So to find out the managers of all the
employees, we need a self-join.
Differences between UNION and UNION ALL in SQL Server:
Both UNION and UNION ALL are used to combines the result-set of two or more select
queries into a single result-set. The difference between these two is UNION removes
duplicate rows whereas UNION ALL does not. When use UNION, to remove the duplicate
rows, the SQL server has to do a distinct sort which is time-consuming. For this reason,
the UNION ALL is much faster than UNION.
If we want to see the cost of DISTINCT SORT, you can turn on the estimated query
execution plan using CTRL + L. For UNION and UNION ALL to work, the Number, Data
types, and the order of the columns in the select statements should be the same.
If we want to sort the results of UNION or UNION ALL the ORDER BY clause should be
used on the last SELECT statement as shown below.
Difference between JOIN and UNION in SQL Server:
JOINS and UNIONS are two different things. However, this question is being asked very
frequently now. UNION combines the result-set of two or more select queries into a single
result-set whereas JOINS retrieves data from two or more tables based on logical
relationships between the tables.
What is a cross join? Explain with an example?
Let us understand Cross Join with an example. Create 2 tables Company and Candidate.
Use the script below to create these tables and populate them. CompanyId column in
Candidate Table is a foreign key referencing CompanyId in Company Table.
CREATE TABLE Company
(
CompanyId TinyInt Identity Primary Key,
CompanyName Nvarchar(50) NULL
)
GO
INSERT Company VALUES('DELL')
INSERT Company VALUES('HP')
INSERT Company VALUES('IBM')
INSERT Company VALUES('Microsoft')
GO
CREATE TABLE Candidate
(
CandidateId tinyint identity primary key,
FullName nvarchar(50) NULL,
CompanyId tinyint REFERENCES Company(CompanyId)
)
GO
INSERT Candidate VALUES('Ron',1)
INSERT Candidate VALUES('Pete',2)
INSERT Candidate VALUES('Steve',3)
INSERT Candidate VALUES('Steve',NULL)
INSERT Candidate VALUES('Ravi',1)
INSERT Candidate VALUES('Raj',3)
INSERT Candidate VALUES('Kiran',NULL)
GO
A cross join produces the Cartesian product of the tables involved in the join. The size of
a Cartesian product result set is the number of rows in the first table multiplied by the
number of rows in the second table. A query involving a CROSS JOIN for
the Candidate and Company Table is shown below.
SELECT Cand.CandidateId,
Cand.FullName,
Cand.CompanyId,
Comp.CompanyId,Comp.CompanyName
FROM Candidate Cand
CROSS JOIN Company Comp
If we run the above query, we produce the result set shown in the image below.

Key Points to remember about CROSS JOIN.


A cross join produces the Cartesian product of the tables involved in the join. This means
every row in the Left Table is joined to every row in the Right Table. The candidate is LEFT
Table and Company is RIGHT Table. In our example, we have 28 total numbers of rows
in the result set. 7 rows in the Candidate table multiplied by 4 rows in the Company Table.
In real-time scenarios, we rarely use a CROSS JOIN. Most often we use either INNER
JOIN or LEFT OUTER JOIN. The CROSS JOIN does not have an ON clause with Join’s
conditions. All the other JOINS use the ON clause with a Join Condition. Using an ON
clause on a CROSS JOIN would generate a syntax error.
What is inner Join in SQL Server? Explain with an example?
Let us understand the Inner join with an example. Create 2
Tables Company and Candidate. We are going to use the following two tables through
out this article. Please use the script below to create these tables and populate them.
CompanyId column in Candidate Table is a foreign key referencing CompanyId in
Company Table.
CREATE TABLE Company
(
CompanyId TinyInt Identity Primary Key,
CompanyName Nvarchar(50) NULL
)
GO
INSERT Company VALUES('DELL')
INSERT Company VALUES('HP')
INSERT Company VALUES('IBM')
INSERT Company VALUES('Microsoft')
GO
CREATE TABLE Candidate
(
CandidateId tinyint identity primary key,
FullName nvarchar(50) NULL,
CompanyId tinyint REFERENCES Company(CompanyId)
)
GO
INSERT Candidate VALUES('Ron',1)
INSERT Candidate VALUES('Pete',2)
INSERT Candidate VALUES('Steve',3)
INSERT Candidate VALUES('Steve',NULL)
INSERT Candidate VALUES('Ravi',1)
INSERT Candidate VALUES('Raj',3)
INSERT Candidate VALUES('Kiran',NULL)
GO
If we want to select all the rows from the LEFT table (In our example Candidate Table)
that have a non-null foreign key value (CompanyId in Candidate Table is the foreign key)
then we use INNER JOIN. A query involving an INNER JOIN for the Candidate and
Company Table is shown below.
SELECT Cand.CandidateId,
Cand.FullName,
Cand.CompanyId,
Comp.CompanyId,
Comp.CompanyName
FROM Candidate Cand
INNER JOIN Company Comp
ON Cand.CompanyId = Comp.CompanyId
If we run the above query the output will be as shown in the image below. If we look at the
output, we only got 5 rows. We did not get the 2 rows that have a NULL value in the
CompanyId column. So, an INNER JOIN would get all the rows from the LEFT table that
has non-null foreign key value.

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

SQL Server Stored Procedure Interview Questions


and Answers
In this article, I am going to discuss the most frequently asked SQL Server Stored
Procedure Interview Questions and Answers. Please read our previous article where
we discussed the SQL Server Exception Handling Interview Questions and Answers.
If you go through the entire article, then definitely at the end of this article, you will be in a
position to answers almost all SQL Server Stored Procedure Interview Questions. As part
of this article, we are going to discuss the following SQL Server Stored Procedure
Interview Questions with Answers.
Advertisements
1. What is a SubProgram in SQL Server?
2. What is a stored procedure or procedure in SQL Server?
3. Why we need the stored procedure?
4. What is the output parameter?
5. What are the stored procedure status variables?
6. Disadvantages of Return status value.
7. What are the advantages of using a stored procedure in SQL
Server?
8. What is an execution plan?
9. When would you use it?
10. How would you view the execution plan?
11. How to view the text of the stored procedure?
12. How to encrypt the text of a stored procedure?
13. What are the different procedure attributes in SQL Server?
14. What is the temporary stored procedure?
15. What are Private / Local Temporary Stored Procedure?
16. What is the Public / Global Temporary Stored Procedure?
17. What is the use of a Temporary Stored Procedure?
18. What is deferred name resolution in SQL Server?
19. Can a stored procedure call itself or recursive stored procedure?
How many level SP nesting possible?
What is SubProgram?
A subprogram in SQL Server is a named block of code that is directly saved on the
database server. Then we can execute this subprogram when and where it is
required. Under the databases, a subprogram is reported as a “stored procedure” or
“stored function” or “database triggers”.
What is a stored procedure or procedure in SQL Server?
In a database management system (DBMS), a stored procedure is a precompiled set of
Structured Query Language (SQL) statements with an assigned name and directly saved
in the database.
The stored procedure in SQL Server can accept both input and output parameters so that
a single stored procedure can be used by several clients over the network by using
different input data. The stored procedure will reduce network traffic and increase
performance. If we modify the body of the stored procedure then all the clients who are
using the stored procedure will get the updated stored procedure.
Why we need the stored procedure?
This is one of the most frequently asked SQL Server Stored Procedure Interview
Questions in the SQL Server Interview. So let’s discuss this question in details
Whenever we want to execute a SQL query from an application the SQL query (statement)
what we send from an application will be first compiled(parsed) for execution, where the
process of compiling(parsing) is time-consuming because compilation occurs each time
when we execute the query or statements.
To overcome the above problem, we write SQL statements or query under the stored
procedure and execute because a stored procedure is a pre-compiled block of code,
without compiling(parsing) the statements get executed whenever the procedures are
called which can increase the performance of database server which ultimately increases
the performance of the application.
If we have a situation where we write the same query again and again, we can save that
specific query as a stored procedure and call it’s just by its name whenever required that
query to execute.
What is the output parameter?
The Parameters of a stored procedure can be of two types
1. Input parameters
2. Output parameters
The Input parameters are basically used for bringing value into the procedure for execution
whereas the output parameters are used for carrying a value out of the procedure after
execution.
If a parameter is declared as output, we only require assigning a value to the parameter
inside the procedure so that the procedure will send that value at the end of procedure
execution.
What are the stored procedure status variables?
Whenever we execute a stored procedure in SQL Server, it always returns an integer
status variable indicating the status, usually, zero indicates success, and non-zero
indicates the failure. To see this yourself, execute any stored procedure from the object
explorer, in SQL Server management studio.
1. Right Click and select ‘Execute Stored Procedure
2. If the procedure, expects parameters, provide the values and click OK
3. Along with the result that you expect, the stored procedure also returns a
Return Value = 0
So, from this point, we understood that, when a stored procedure is executed, it returns
an integer status variable. With this in mind, let’s understand the difference between the
output parameters and RETURN values in SQL Server stored procedure.
We are going to use the following Employee table to understand the Stored Procedure
Output Parameters and Return values in SQL Server.

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

Create procedure spGetCustomers


As
Begin
Select * from Customers
End
Customers table does not exist. When we execute the above SQL code, the stored
procedure spGetCustomers will be successfully created without errors. But when you try
to call or execute the stored procedure using Execute spGetCustomers, we will get a
runtime error stating Invalid object name ‘Customers’.
So, at the time of creating stored procedures, only the syntax of the SQL code is checked.
The objects used in the stored procedure are not checked for their existence. Only when
we try to run the procedure, the existence of the objects is checked. So, the process of
postponing, the checking of the physical existence of the objects until runtime, is called
deferred name resolution in the SQL Server.
Functions in SQL server does not support deferred name resolution. If we try to create
an inline table-valued function as shown below, we get an error stating Invalid object name
‘Customers’ at the time of the creation of the function itself.
Create function fnGetCustomers()
returns table
as
return Select * from Customers
So, this proves that stored procedures support deferred name resolution, whereas
function does not. In fact, this is one of the major differences between functions and stored
procedures in SQL Server.
Can a stored procedure call itself or recursive stored procedure? How
many level SP nesting possible?
Yes. Because Transact-SQL supports recursion, you can write stored procedures that call
themselves. Recursion can be defined as a method of problem solving wherein the
solution is arrived at by repetitively applying it to subsets of the problem. A common
application of recursive logic is to perform numeric computations that lend themselves to
repetitive evaluation by the same processing steps. Stored procedures are nested when
one stored procedure calls another or executes managed code by referencing a CLR
routine, type, or aggregate. You can nest stored procedures and managed code
references up to 32 levels.
SQL Server Functions Interview Questions and
Answers
In this article, I am going to discuss the most frequently asked SQL Server Functions
Interview Questions and Answers. Please read our previous article where we discussed
the most frequently asked SQL Server Views Interview Questions and Answers. As part
of this article, we are going to discuss the following SQL Server Functions Interview
Questions with answers.
Advertisements
1. What is a function in SQL Server?
2. Types of User-Defined Functions in SQL Server
3. What is a scalar function in SQL Server?
4. What is a table-valued function?
5. Where can we use the Inline Table-Valued function?
6. What is Inline table-valued functions?
7. What are Multi-Statement Table-Valued Functions in SQL Server?
8. Differences between Inline Table-Valued functions and Multi-
statement Table-Valued functions.
9. What are the differences between functions and procedures in
SQL Server?
What is a function in SQL Server?
A function is a database object in SQL Server. Basically, it is a set of SQL statements that
accept only input parameters, perform actions, and return the result. The function can
return only a single value or a table. We can’t use the function to Insert, Update, and
Delete records in the database table(s).
1. It is also a subprogram like a stored procedure that is defined for
performing an action such as complex calculation and returns the result of
the action as a value.
2. These functions are created by the user or programmer.
3. Functions are taking some parameters, do some processing, and
returning some results back
For example Select SQUARE(3) Output: 9
Some functions also do not take any parameters. For Example: Select GETDATE()
So, we can say that a function can have the parameter that is optional but a function
should return a value that is mandatory.
Types of User-Defined Functions in SQL Server:
In SQL Server, there are 3 types of User-Defined Functions
1. Scalar functions
2. Inline table-valued functions
3. Multi-statement table-valued functions
What is a scalar function in SQL Server?
The functions which return a single value are known as scalar value function. The Scalar
functions may or may not have parameters, but always return a single (scalar) value. The
returned value can be of any data type, except text, ntext, image, cursor, and
timestamp.
To create a function, we use the following syntax:

What is a table-valued function?


In this case, we can return a table as an output from the function. These are again of two
types
1. Inline Table-valued Function
2. Multi-statement table value function
Where can we use the Inline Table-Valued function?
The Inline Table-Valued functions can be used to achieve the functionality of
parameterized views. The table returned by the table-valued function can also be used in
joins with other tables.
What is Inline table-valued functions?
In this case, the body of the function will have only a single select statement prepared with
the “RETURN” statement. The syntax for creating a table value function
CREATE/ALTER FUNCTION <FUNCTION NAME>(@<VARIABLE NAME><DATA
TYPE> [SIZE])
RETURNS TABLE
AS
RETURN <SELECT STATEMENT>
1. We specify the Table as the return type instead of any scalar data type.
2. The function body is not closed between BEGIN and END block
3. The structure of the table that gets returned is determined by the select
statement within the function.
What are Multi-Statement Table-Valued Functions in SQL Server?
This is the same as the inline table-valued function which can return a table as an output
but here the body can contain more than one statement and also the structure of the table
being returned can be defined. The Syntax is given below.
CREATE/ALTER FUNCTION <FUNCTIONNAME> (@<PARAM><DATATYPE>
[SIZE].....)
RETURNS @<TABLE VAR> TABLE (<COLUMN DEFINITIONS>)
[WITH <FUNCTION ATTRIBUTES>]
AS
BEGIN
<FUNCTION BODY>
RETURN
END
Note: In case of a multi-statement table-valued function we need to define our own
structure to the table being return.
Differences between Inline Table-Valued functions and Multi-statement
Table-Valued functions
In an Inline Table-Valued function, the RETURNS clause cannot contain the structure of
the table, the function returns. Whereas, with the multi-statement table-valued function,
we specify the structure of the table that gets returned
Inline Table-Valued function cannot have BEGIN and END block as it returns a single
select statement, whereas the multi-statement function can have the begin and end block
as it contains more than one select statement.
Inline Table-valued functions are better for performance than multi-statement table-valued
functions. If the given task, can be achieved using an inline table-valued function, always
prefer to use them, over multi-statement table-valued functions.
It’s possible to update the underlying table, using an inline table-valued function, but not
possible using a multi-statement table-valued function.
Reason for improved performance of an inline table-valued function:
Internally, SQL Server treats an inline table-valued function much like it would a view and
treats a multi-statement table-valued function similar to how it would a stored procedure.
What are the differences between functions and procedures in SQL
Server?
Stored Procedures are pre-compiled objects which are compiled for the first time and its
compiled format is saved which executes (compiled code) whenever it is called. But
Function is compiled and executed every time when it is called.
BASIC DIFFERENCE
1. The function must return a value but in Stored Procedure, it is optional
(Procedure can return zero or n values).
2. Functions can have only input parameters whereas Procedures can have
input/output parameters.
3. A Function can be called from Procedure whereas Procedures cannot be
called from Function
4. From a procedure, we can call another procedure or a function whereas
from a function we can call another function but not a procedure.
ADVANCE DIFFERENCE
1. The procedure allows SELECT as well as DML
(INSERT/UPDATE/DELETE) statement in it whereas Function allows only
SELECT statement in it.
2. Procedures cannot be utilized in a SELECT statement whereas Function
can be embedded in a SELECT statement.
3. Stored Procedures cannot be used in the SQL statements anywhere in the
WHERE/HAVING/SELECT section whereas Function can be.
4. Functions that return tables can be treated as a row set. This can be used
in JOINs with other tables
5. The exception can be handled by a try-catch block in a procedure
whereas a try-catch block cannot be used in a Function.
6. We can go for Transaction Management in Procedure whereas we can’t
go into Function.
7. We call a procedure using EXECUTE/ EXEC command whereas a
function is called by using the SELECT command only.
8. Stored procedures support deferred name resolution. For example, while
writing a stored procedure that uses table names, for example, table1,
table2, etc. but these tables do not exist in the database is allowed during
the creation of the stored procedure but runtime throws error whereas
functions do not support deferred name resolution.
ASP.NET Web API
1. It is a framework that helps us to develop HTTP Based services i.e.
Restful Services.
2. Web API is an open-source platform.
3. It supports most of the MVC features which keep Web API over WCF.
When do we need to choose ASP.NET Web API?
Today, a web-based application is not enough to reach its customers. Now a day, people
have become very smart; they are using iPhones, mobiles, tablets, etc. devices in their
daily life. These devices are having a lot of apps that actually make their life easy. Actually,
we are moving from the web towards the apps world.
So, if we like to expose our service data to the browsers as well as to all these modern
device apps in a fast, simple, and secure way, then we should have an API that is
compatible with browsers as well as with all these modern devices.
The ASP.NET WEB API is a great framework for building HTTP services i.e. Restful
Services that can be consumed by a broad range of clients including browsers, mobiles,
iPhones, and tablets, etc.
What is the difference between WCF and WEB API and WCF
REST and Web Service?
The .NET framework has a number of technologies that allow us to create HTTP services
such as Web Service, WCF, WCF Rest, and now WEB API. Following are the differences
between these four:
Web Service:
1. The Web Service is based on SOAP and it returns the data in XML format.
2. It supports only the HTTP protocol.
3. Web Service is not open-source but it can be consumed by any client who
understands XML.
4. It can only be hosted on IIS.
WCF:
1. WCF is also based on SOAP and it also returns the data in the form of XML.
2. Unlike Web service, WCF supports different types of protocols (transport
protocol) such as TCP, Named Pipes, HTTP, HTTPS, and MSMQ.
3. The main problem with the WCF service it required lots of configuration
which is a headache for a developer.
4. Like Web Service, WCF is also not open source but it can be consumed
by any client who understands XML.
5. WCF can be host within the application or on IIS or using Windows service.
WCF Rest:
1. To use a WCF service as WCF Rest service we have to enable
webHttpBindings.
2. WCF Rest supports the HTTP verbs such as GET and POST by using the
[WebGet] and [WebInvoke] attributes respectively.
3. To use other HTTP verbs you have to do some configuration in the IIS so
that it will accept the request of that particular verb on the .svc file
4. It supports different data formats such as XML, JSON, and Atom format.
WEB API:
1. The Web API Framework is a new framework that is basically used for
developing HTTP-based services in an easy and simple way.
2. Unlike WCF Rest Service, it uses full HTTP features such as URIs,
request/response headers, caching, versioning, and various data formats.
3. The ASP.NET Web API also supports most of the MVC features such as
routing, controllers, actions, filter, model binders, IOC container,
dependency injection, unit testing which makes it more simple and robust.
4. WEB API Services can be hosted on IIS or within the application
5. The Responses in Web API Services are formatted by
MediaTypeFormatter into JSON, XML, or any custom format you want.
What are the advantages of using REST in ASP.NET Web API?
The REST uses fewer data transfers between client and server which makes REST
ideal for use in mobile apps. The ASP.NET Web API supports HTTP Protocols and
thereby it reintroduces the old way of HTTP verbs for communication.
What are the Differences between WCF Rest and Web API?
WCF Rest
1. We need to use WebHttpBinding to be enabled for WCF Rest.
2. For each method, there have to be attributes like – “WebGet” and
“WebInvoke”
Web API
1. Unlike WCF Rest, we can use full features of HTTP in Web API.
2. Web API can be hosted in IIS or in an application.
What are the advantages of using ASP.NET Web API?
Using ASP.NET Web API has a number of advantages, but the core advantages are as
follows:
1. It supports all the HTTP features and allows all standard HTTP verbs such
as GET, POST, PUT, PATCH, and DELETE to perform CRUD operations
2. Complete support for Routing which is good for SEO.
3. It supports content negotiation i.e. as per the client request, the server
sends the response in that format (if possible). The Response generated in
JSON or XML format using MediaTypeFormatter
4. It has the ability to be hosted in IIS as well as self-host outside of IIS
5. Supports Model binding and Validation
What new features are introduced in ASP.NET Web API 2.0?
The new features introduced in ASP.NET Web API framework v2.0 are as follows:
1. Attribute Routing
2. External Authentication (third party authentication)
3. CORS (Cross-Origin Resource Sharing)
4. OWIN (Open Web Interface for .NET) Self Hosting
5. IHttpActionResult
What are the differences between ASP.NET MVC and ASP.NET Web
API?
This is one of the frequently asked ASP.NET Web API Interview Questions. The following
are some of the differences between ASP.NET MVC and ASP.NET Web API
MVC
1. ASP.NET MVC Framework basically used to create a web application by
following the MVC (Model-View-Controller) design pattern, in which we can
build web pages.
2. The action method can return both data and view. It only returns data in
JSON format using JsonResult
3. All requests are mapped to the respective action based on the action
method names.
4. Content-negotiation not supported.
Web API
1. ASP.NET Web API Framework is used to develop Restful services that
can be consumed by different clients.
2. Web API returns data in a particular format like JSON, XML, or any other
based upon the Accept header in the request. It does not return the view to
the client.
3. All requests are mapped to actions using HTTP verbs.
4. Content-negotiation supported.
Note: We can mix Web API and MVC controller in a single project to handle advanced
AJAX requests which may return data in JSON, XML, or any other format, and building a
full-blown HTTP service. Typically, this will be called Web API self-hosting.
Is it true that ASP.NET Web API has replaced WCF?
It’s not true. It’s a misconception that ASP.NET Web API has replaced WCF. ASP.NET
Web API is just another way of building non-SOAP-based services, for example, plain
XML or JSON string, etc.
Yes, ASP.NET Web API has some added advantages like utilizing the full features of
HTTP (HTTP Built-in Header and HTTP Verbs such as GET, POST, PUT, PATCH, and
DELETE, HTTP Status codes such as 500, 200, 404, etc.) and reaching more clients such
as mobile devices, Tables, IoTs, Browsers, etc. But WCF is still a good choice for the
following scenarios:
1. If you want to develop transport protocol-oriented services other than
HTTP, such as TCP, UDP, or Named Pipes, etc. If HTTP only then go with
Web API.
2. Message Queuing scenario using MSMQ
3. One-way communication or Duplex communication
Explain Media Formatters in Web API 2
It is one of the frequently asked ASP.NET Web API Interview Questions. As we know that
Web API Framework handles the data in JSON or XML formats (or any other formats)
based on the Accept and Content-Type header values. But do you know how does the
ASP.NET Web API Framework handles these different formats? The answer is by
using Media Type Formatters.
The Media-Type Formatters are classes that are responsible for serializing the
request/response data. Based on the accept and content-type header values the
ASP.NET Web API Framework can understand the request data format and sends the
data in the format which the client expects.
Technically MediaTypeFormatter is an abstract class from
which JsonMediaTypeFormatter and XmlMediaTypeFormatter classes inherit from.
JsonMediaTypeFormatter handles JSON data and XmlMediaTypeFormatter handles XML
data.
How to return JSON from Web API Service irrespective of the Accept
header value?
To do so, we need to remove the XmlFormatter from the Register() method of
WebApiConfig.cs file which is present inside the App_Start folder. To remove
XmlFormatter include the following piece of code that will completely remove
XmlFormatter which forces ASP.NET Web API to always return data in JSON format
irrespective of the Accept header value in the client request. Use this technique when you
want your service to support only JSON and not XML.
config.Formatters.Remove(config.Formatters.XmlFormatter);
With this change in place inside the Register method of the WebApiConfig class,
irrespective of the Accept header value (application/xml or application/json), the Web API
service is always going to return the data in JSON format.
How to return XML data from Web API Service irrespective of the
Accept header value?
To do so, we need to remove the JsonFormatter from the Register() method of
WebApiConfig.cs file which is present inside the App_Start folder. To remove we can
include the following piece of code that will completely remove JsonFormatter which forces
ASP.NET Web API to always return XML irrespective of the Accept header value in the
client request. Use this technique when you want your service to support only XML and
not JSON.
config.Formatters.Remove(config.Formatters.JsonFormatter);
With this change in place inside the Register method of the WebApiConfig class,
irrespective of the Accept header value (application/xml or application/json), the Web API
service is always going to return the data in XML format.
How to return JSON instead of XML from Web API Service when a
request is made from the browser?
So here is what we want the service to do
1. When a request is issued from the browser, the ASP.NET Web API
service should return the data in JSON format instead of XML.
2. When a request is issued from a tool like a fiddler or Postman, the Accept
header value should be respected. That means if the Accept header value
is set to application/xml the service should return XML and if the Accept
header value is set to application/json the service should return the data
in JSON.
There are 2 ways to achieve this
Approach1:
Include the following line in Register() method of WebApiConfig.cs file in the App_Start
folder. This tells ASP.NET Web API to use JsonFormatter when a request is made for
text/html which is the default for most browsers. The problem with this approach is that
the Content-Type header of the response is set to text/html which is misleading.
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHead
erValue(“text/html”));
Approach2:
Include the following class in WebApiConfig.cs file in the App_Start folder.
Register Formatter:
Place the following line in Register() method of WebApiConfig.cs file in App_Start folder

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.

2) Differentiate between file and structure storage structure.


The key difference between both the data structure is the memory area that is
being accessed. When dealing with the structure that resides the main
memory of the computer system, this is referred to as storage structure. When
dealing with an auxiliary structure, we refer to it as file structures.
Free PDF Download: Data Structures Interview Questions & Answers

3) When is a binary search best applied?


A binary search is an algorithm that is best applied to search a list when the
elements are already in order or sorted. The list is searched starting in the
middle, such that if that middle value is not the target search key, it will check
to see if it will continue the search on the lower half of the list or the higher
half. The split and search will then continue in the same manner.

4) What is a linked list?


A linked list is a sequence of nodes in which each node is connected to the
node following it. This forms a chain-like link for data storage.

5) How do you reference all the elements in a one-


dimension array?
To reference all the elements in a one -dimension array, you need to use an
indexed loop, So that, the counter runs from 0 to the array size minus one. In
this manner, You can reference all the elements in sequence by using the loop
counter as the array subscript.

6) In what areas do data structures are applied?


Data structures are essential in almost every aspect where data is involved. In
general, algorithms that involve efficient data structure is applied in the
following areas: numerical analysis, operating system, A.I., compiler design,
database management, graphics, and statistical analysis, to name a few.

Data Structures Interview


Questions

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.

Binary Search Tree

10) Which data structures are applied when dealing with a


recursive function?
Recursion, is a function that calls itself based on a terminating condition,
makes use of the stack. Using LIFO, a call to a recursive function saves the
return address so that it knows how to return to the calling function after the
call terminates.

11) What is a stack?


A stack is a data structure in which only the top element can be accessed. As
data is stored in the stack, each data is pushed downward, leaving the most
recently added data on top.
12) Explain Binary Search Tree
A binary search tree stores data in such a way that they can be retrieved very
efficiently. The left subtree contains nodes whose keys are less than the node’s
key value, while the right subtree contains nodes whose keys are greater than
or equal to the node’s key value. Moreover, both subtrees are also binary
search trees.

13) What are multidimensional arrays?


Multidimensional arrays make use of multiple indexes to store data. It is useful
when storing data that cannot be represented using single dimensional
indexing, such as data representation in a board game, tables with data stored
in more than one column.

14) Are linked lists considered linear or non-linear data


structures?
It depends on where you intend to apply linked lists. If you based it on
storage, a linked list is considered non-linear. On the other hand, if you based
it on access strategies, then a linked list is considered linear.

15) How does dynamic memory allocation help in managing


data?
Apart from being able to store simple structured data types, dynamic memory
allocation can combine separately allocated structured blocks to form
composite structures that expand and contract as needed.
16) What is FIFO?
FIFO stands for First-in, First-out, and is used to represent how data is
accessed in a queue. Data has been inserted into the queue list the longest is
the one that is removed first.

17) What is an ordered list?


An ordered list is a list in which each node’s position in the list is determined
by the value of its key component, so that the key values form an increasing
sequence, as the list is traversed.

18) What is merge sort?


Merge sort, is a divide-and-conquer approach for sorting the data. In a
sequence of data, adjacent ones are merged and sorted to create bigger
sorted lists. These sorted lists are then merged again to form an even bigger
sorted list, which continues until you have one single sorted list.

19) Differentiate NULL and VOID


Null is a value, whereas Void is a data type identifier. A variable that is given a
Null value indicates an empty value. The void is used to identify pointers as
having no initial size.

20) What is the primary advantage of a linked list?


A linked list is an ideal data structure because it can be modified easily. This
means that editing a linked list works regardless of how many elements are in
the list.
21) What is the difference between a PUSH and a POP?
Pushing and popping applies to the way data is stored and retrieved in a stack.
A push denotes data being added to it, meaning data is being “pushed” into
the stack. On the other hand, a pop denotes data retrieval, and in particular,
refers to the topmost data being accessed.

22) What is a linear search?


A linear search refers to the way a target key is being searched in a sequential
data structure. In this method, each element in the list is checked and
compared against the target key. The process is repeated until found or if the
end of the file has been reached.

23) How does variable declaration affect memory allocation?


The amount of memory to be allocated or reserved would depend on the data
type of the variable being declared. For example, if a variable is declared to be
of integer type, then 32 bits of memory storage will be reserved for that
variable.

24) What is the advantage of the heap over a stack?


The heap is more flexible than the stack. That’s because memory space for the
heap can be dynamically allocated and de-allocated as needed. However, the
memory of the heap can at times be slower when compared to that stack.

25) What is a postfix expression?


A postfix expression is an expression in which each operator follows its
operands. The advantage of this form is that there is no need to group sub-
expressions in parentheses or to consider operator precedence.
26) What is Data abstraction?
Data abstraction is a powerful tool for breaking down complex data problems
into manageable chunks. This is applied by initially specifying the data objects
involved and the operations to be performed on these data objects without
being overly concerned with how the data objects will be represented and
stored in memory.

27) How do you insert a new item in a binary search tree?


Assuming that the data to be inserted is a unique value (that is, not an existing
entry in the tree), check first if the tree is empty. If it’s empty, just insert the
new item in the root node. If it’s not empty, refer to the new item’s key. If it’s
smaller than the root’s key, insert it into the root’s left subtree, otherwise,
insert it into the root’s right subtree.

28) How does a selection sort work for an array?


The selection sort is a fairly intuitive sorting algorithm, though not necessarily
efficient. In this process, the smallest element is first located and switched with
the element at subscript zero, thereby placing the smallest element in the first
position.

The smallest element remaining in the subarray is then located next to


subscripts 1 through n-1 and switched with the element at subscript 1, thereby
placing the second smallest element in the second position. The steps are
repeated in the same manner till the last element.

29) How do signed and unsigned numbers affect memory?


In the case of signed numbers, the first bit is used to indicate whether positive
or negative, which leaves you with one bit short. With unsigned numbers, you
have all bits available for that number. The effect is best seen in the number
range (an unsigned 8-bit number has a range 0-255, while the 8-bit signed
number has a range -128 to +127.
30) What is the minimum number of nodes that a binary tree
can have?
A binary tree can have a minimum of zero nodes, which occurs when the
nodes have NULL values. Furthermore, a binary tree can also have 1 or 2
nodes.

31) What are dynamic data structures?


Dynamic data structures are structures that expand and contract as a program
runs. It provides a flexible means of manipulating data because it can adjust
according to the size of the data.

32) In what data structures are pointers applied?


Pointers that are used in linked list have various applications in the data
structure. Data structures that make use of this concept include the Stack,
Queue, Linked List and Binary Tree.

33) Do all declaration statements result in a fixed reservation


in memory?
Most declarations do, with the exemption of pointers. Pointer declaration does
not allocate memory for data, but for the address of the pointer variable.
Actual memory allocation for the data comes during run-time.

34) What are ARRAYs?


When dealing with arrays, data is stored and retrieved using an index that
refers to the element number in the data sequence. This means that data can
be accessed in any order. In programming, an array is declared as a variable
having a number of indexed elements.
35) What is the minimum number of queues needed when
implementing a priority queue?
The minimum number of queues needed in this case is two. One queue is
intended for sorting priorities while the other queue is used for actual storage
of data.

36) Which sorting algorithm is considered the fastest?


There are many types of sorting algorithms: quick sort, bubble sort, balloon
sort, radix sort, merge sort, etc. Not one can be considered the fastest because
each algorithm is designed for a particular data structure and data set. It
would depend on the data set that you would want to sort.

37) Differentiate STACK from ARRAY.


Stack follows a LIFO pattern. It means that data access follows a sequence
wherein the last data to be stored when the first one to be extracted. Arrays,
on the other hand, does not follow a particular order and instead can be
accessed by referring to the indexed element within the array.

38) Give a basic algorithm for searching a binary search tree.


1.if the tree is empty, then the target is not in the tree, end search
2. if the tree is not empty, the target is in the tree
3. check if the target is in the root item
4. if a target is not in the root item, check if a target is smaller than the root’s
value
5. if a target is smaller than the root’s value, search the left subtree
6. else, search the right subtree
39) What is a dequeue?
A dequeue is a double-ended queue. This is a structure wherein elements can
be inserted or removed from either end.

40) What is a bubble sort and how do you perform it?


A bubble sort is one sorting technique that can be applied to data structures
such as an array. It works by comparing adjacent elements and exchanges
their values if they are out of order. This method lets the smaller values
“bubble” to the top of the list, while the larger value sinks to the bottom.

41) What are the parts of a linked list?


A linked list typically has two parts: the head and the tail. Between the head
and tail lie the actual nodes. All these nodes are linked sequentially.

42) How does selection sort work?


Selection sort works by picking the smallest number from the list and placing
it at the front. This process is repeated for the second position towards the
end of the list. It is the simplest sort algorithm.

43) What is a graph?


A graph is one type of data structure that contains a set of ordered pairs.
These ordered pairs are also referred to as edges or arcs and are used to
connect nodes where data can be stored and retrieved.

44) Differentiate linear from a nonlinear data structure.


The linear data structure is a structure wherein data elements are adjacent to
each other. Examples of linear data structure include arrays, linked lists, stacks,
and queues. On the other hand, a non-linear data structure is a structure
wherein each data element can connect to more than two adjacent data
elements. Examples of nonlinear data structure include trees and graphs.

45) What is an AVL tree?


An AVL tree is a type of binary search tree that is always in a state of partially
balanced. The balance is measured as a difference between the heights of the
subtrees from the root. This self-balancing tree was known to be the first data
structure to be designed as such.

AVL tree

46) What are doubly linked lists?


Doubly linked lists are a special type of linked list wherein traversal across the
data elements can be done in both directions. This is made possible by having
two links in every node, one that links to the next node and another one that
connects to the previous node.

47) What is Huffman’s algorithm?


Huffman’s algorithm is used for creating extended binary trees that have
minimum weighted path lengths from the given weights. It makes use of a
table that contains the frequency of occurrence for each data element.
48) What is Fibonacci search?
Fibonacci search is a search algorithm that applies to a sorted array. It makes
use of a divide-and-conquer approach that can significantly reduce the time
needed in order to reach the target element.

49) Briefly explain recursive algorithm.


Recursive algorithm targets a problem by dividing it into smaller, manageable
sub-problems. The output of one recursion after processing one sub-problem
becomes the input to the next recursive process.

50) How do you search for a target key in a linked list?


To find the target key in a linked list, you have to apply sequential search. Each
node is traversed and compared with the target key, and if it is different, then
it follows the link to the next node. This traversal continues until either the
target key is found or if the last node is reached.

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

ADO.NET being one of the products of Microsoft, it is good enough to position


itself strongly in the market. ADO.NET has massive community support, so it is
definitely having a large scope ahead. You could learn ADO.NET along with hands-
on experience on the .Net frame

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 Interview Questions for Freshers


1. What is 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.

2. What is DataSet in ADO.NET?

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

3. Give the differences between ADO and ADO.NET.


ADO ADO.NET

It is Component Object Modelling(COM)


It is Common Language Runtime(CLR) based.
based.

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.

It provides a feature of locking. It does not provide a feature of locking.

Data is stored in binary form. Data is stored in XML.

It does not support XML integration. It supports XML integration.

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

Both client-side and server-side cursors can be


We can create only client-side cursors.
created.

It supports sequential row access in a Non-sequential data access is supported in


RecordSet. DataSet by using a collection-based hierarchy.

It will make use of DataRelational objects to


It will make use of SQL JOINs and UNIONs
combine data from multiple tables without the
for combining data from multiple tables. It
help of JOINs and UNIONs. Therefore records
is not possible to fetch records from
from multiple tables are maintained
multiple tables independently.
independently.

4. What is a DataAdapter in ADO.NET?

• A DataAdapter is used to access data from a data source by functioning as a bridge


between DataSet and a data source. DataAdapter class includes an SQL command
set and a database connection. It is helpful to fill the DataSet and resolve changes to
the data source.
• The DataAdapter will make use of the Connection object that belongs to the .NET
Framework data provider for connecting with a data source. Along with that, it will
also use Command objects to retrieve data from the data source as well as to
resolve changes to the data source.
• DataAdapter properties that permit the user to control the database are the Select
command, Update command, Insert command, and Delete command.
• Example code for the usage of DataAdapter:

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.

5. Explain the difference between ADO.NET and ASP.NET.


ADO.NET(ActiveX Data Objects) ASP.NET(Active Server Pages)

ADO.NET is a Library within the .NET framework. ASP.NET is a Framework.

It is a technology useful for accessing data from It is a technology useful for the creation
databases. of dynamic web pages.

Here, We can write our code into


Here, data can be converted into XML format.
VB.Net, C#, ASP.Net, etc.

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.

6. Explain about DataSet types in ADO.NET.

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.

Example program for the usage of DataSet:

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.

7. Explain the difference between DataTable and DataSet.


DataTable DataSet

DataTable consists of a single database DataSet consists of a collection of multiple


table that is placed within a memory. database tables which is placed within a memory.

It has a row and column collection. It has a database table collection.

It allows fetching only a single TableRow


It allows fetching multiple TableRows at a time.
at a time.

It represents a collection of DataTable objects, so


It is a single database table, so there will
there might be a relation between them to obtain
not be any relation with other tables.
a particular result.

In this, DataSource objects are not


In this, DataSource objects are serialized.
serialized.

UniqueConstraint and
UniqueConstraint and ForeignKeyConstraint
ForeignKeyConstraint objects are not
objects are available for enforcing data integrity.
available enforcing data integrity.

8. What are the different namespaces available in ADO.NET?

Various namespaces available under ADO.NET is given below:

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.

9. What is object pooling?

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.

10. Differentiate DataSet and DataReader.


DataSet DataReader

DataSet provides read/write access to data, so DataReader provides read-only access to


we can update the data. data, so we can’t update the data.

It has a disconnected architecture, which means It has a connected architecture, which


the data obtained from the database can be means to access the data retrieved from
accessed even after the database connection was the database, the connection must be
closed. opened.

It supports various database tables from different It supports only a single table from a
databases. single database.

It provides slower access to data due to


It provides faster access to data.
overhead.

Both forward and backward scanning of data is


Only forward scanning of data is possible.
possible.

11. What are the different execute() methods available in ADO.NET?

Different execute() methods supported by SqlCommandObject in ADO.NET is given


below:

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

12. What is a transaction in ADO.NET? Explain the types of transactions available in


ADO.NET.

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.

Two types of transactions supported by ADO.NET are as follows:

• 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

An API(Application Programming Interface)


It is an API for accessing DBMS (DataBase
that allows accessing data from different
Management System).
sources in a uniform manner.

It supports both relational and non-


It supports only relational databases.
relational databases.

It is procedural-based. It is component-based.

It is easier to deploy. It is difficult to deploy.

It gives a higher performance on loading It performs less compared to OLE DB on loading


and extracting the data. and extraction of data.

resource odbc_connect(string datasource , string


OleDbConnection = New
username , string password , [int cursor_type ]) is
OleDbConnection(connetionString) is used to
used to make a connection to an ODBC data
OLEDB ODBC

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.

14. What is data binding in ADO.NET?

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

15. What is Connection pooling?

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.

16. What is DataTable in ADO.NET?

DataTable in ADO.NET represents a single table in a DataSet that has in-memory


relational data. The data within DataTable is local to the .NET framework-based
application to which it belongs but can be populated using a DataAdapter from
different data sources such as Microsoft SQL Server. The DataTable class belongs
to the System.Data namespace within the library of .NET Framework.

DataTable can be represented in .aspx.cs code as given below:

protected void DataTableExample()


{
SqlConnection conn = new SqlConnection("Write the database connection string");
conn.Open();
SqlCommand cd = new SqlCommand("Write the query or procedure", conn);
SqlDataAdapter d = new SqlDataAdapter(cd);
DataTable dt = new DataTable();
d.Fill(dt);
grid.DataSource = dt;
grid.DataBind();
}

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?

Some of the properties provided by the DataReader are as follows:

• Depth: It represents the depth of nesting for a row.


• FieldCount: It gives the total column count in a row.
• Item: It obtains the column value in a native format.
• RecordsAffected: It gives the number of transaction affected rows.
• IsClosed: It represents whether a data reader is closed.
• VisibleFieldCount: It is used to obtain the number of unhidden fields in the
SqlDataReader.

Some of the methods provided by the DataReader are as follows:

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

18. What are the conditions for connection pooling?

The conditions for connection pooling are:

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

19. What are the data providers in ADO.NET?

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.

20. Why Stored Procedure is used in ADO.NET?

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

ADO.NET Interview Questions for Experienced


1. Explain ADO.NET Architecture.

ADO.NET is based on an Object Model where data residing in the database is


accessed using a data provider. It is a technology of data access given by the
Microsoft .Net Framework, which helps to communicate between relational and
non-relational systems using a common group of components.

The components of ADO.NET architecture are:

• 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:

• In disconnected architecture, even if the database connection is closed, data


retrieved from the database can be accessed. Disconnected architecture is based on
classes connection, CommandBuilder, DataAdapter, DataSet, and DataView.
• Here, we retrieve and store a recordset from the database so that you can perform
many CRUD (Create, Read, Update, and Delete) operations on the data within
memory, it will be re-synchronized when you reconnect with the database.
• DataSet is a Disconnected Architecture because all records are brought at once and
holding the database connection alive is not necessary.

3. Explain about ExecuteScalar() in ADO.NET.

• 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:

public void ExecuteScalarExample()


{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
try
{
SqlCommand cd = new SqlCommand();
cd.Connection = con;
cd.CommandText = "SELECT SUM(SALARY) FROM EMPLOYEE";
cd.CommandType = CommandType.Text;
con.Open();
Int32 SalaryTotal = Convert.ToInt32(cd.ExecuteScalar());
MessageBox.Show("Total Salary of the employee is : " + SalaryTotal.ToString());
cd.Dispose();
con.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Here, we create an object of the class SqlConnection and SqlCommand. We pass


SQL Statement to the object of SqlCommand class, which returns a single value.
When ExecuteScalar() function gets executed, a single value will be returned, i.e, the
total salary of employees. This value will be displayed using a message box.

4. Explain about ADO.NET objects.

There are seven main objects in ADO.NET. They are:

1. DataSet: It is available under both System.Data.ADO and


the System.Data.SQL namespaces. DataSet is a database cache built-in memory for
using it in disconnected operations. It holds the complete collection of tables,
constraints, and relationships.
2. SQLDataSetCommand: It represents a stored procedure or a database query that
can be used to populate the DataSet object. It corresponds to the ADO’s Command
object-provided functionalities.
3. SQLCommand: It represents a stored procedure or a T-SQL statement that will be
executed by SQL Server. It corresponds to another set of functionalities provided by
the ADO’s Command object.
4. SQLParameter: It can be used to pass parameters to the object of SQLCommand or
SQLDataSetCommand class. When you are passing a parameter for SQLCommand
using SQLParameter, SQLParameter will represent a parameter that can be used by
T-SQL statement or stored procedure. Whenever a parameter has been passed for
SQLDataSetCommand using SQLParameter, SQLParameter will represent a column
from a result set.
5. SQLConnection: It represents an open connection to the data source like SQL
Server. This object is similar to the standard Connection object in ADO.
6. SQLDataReader: It reads a forward-only stream of data from a SQL Server
database. It works with an open database connection.
7. SQLError: It collects runtime warnings and error conditions related information that
will be encountered by an ADO.NET application. It corresponds to ADO’s Error
object.
5. What are the different authentication techniques used to connect with MS SQL
Server?

Before performing any task in the database, SQL Server will authenticate. Two
types of authentication techniques are:

• Windows Authentication: This default authentication is provided only through


Windows domain accounts. This SQL Server security model is strongly integrated
with Windows, so it is also referred to as integrated security. Particular Windows
users and group accounts are allowed to login into SQL Server. Windows users who
are already been authenticated or logged onto Windows do not have to provide
additional credentials.
The below-given SqlConnection.ConnectionString specifies Windows authentication
without any need of providing a user name or password by the user.

C#
"Server=MSSQL1;Database=Institute;Integrated Security=true;

• SQL Server and Windows Authentication Mode(Mixed-mode): Authentication will


be provided with the help of the Windows and SQL Server Authentication
combination. User name and password pair will be maintained within SQL Server. In
order to use this mixed-mode authentication, you need to create SQL Server logins
that are stored in SQL Server. After that, you can supply the user name and
password to SQL Server at run time.

The below-given ConnectionString specifies Mixed mode authentication:

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?

• Response.Expires property is specific to the minutes that a particular page stays in


the cache for the specific time from the time it has been requested. For example,
if Response.Expires value is set to 5 minutes, then the page is instructed to be in
cache for 5 minutes from the time it has been requested.
• Response.ExpiresAbsolute property helps to provide the proper time at which a
specific page cache has been expired. For
example, Response.ExpiresAbsolute provides information like 14 March 15:40:15. This
time tells about when the page was in cache.

7. How to load multiple tables into a dataset?


DataSet ds=new DataSet();
SqlConnection con=new SqlConnection("connection_string");
SqlDataAdapter da=new SqlDataAdapter("select * from Employee1",con);
da.Fill(ds.Tables.Add());
da=new SqlDataAdapter("select * from Employee2",con);
da.Fill(ds.Tables.Add());
After tables have been added into a DataSet, the below-given code tells about how
to make use of the DataSet tables. If you decide to use the first table in a dataset or
to copy the table data into a data table, then follow the below-given code:

DataTable dt=new DataTable();


dt=ds.Tables[0];

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.

8. What is the difference between connected and disconnected architecture in


ADO.NET?
Connected architecture Disconnected architecture

It is connection-oriented. It is not connection-oriented.

DataReader is a connected architecture. DataSet is a disconnected architecture.

High speed and performance are given by Disconnected methods are low in speed and
connected methods. performance.

Data persistence is not possible using


Data persistence is possible using DataSet.
DataReader.

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?

• LINQ(Language Integrated Query) is a structured query syntax that helps the


programmers and testers to retrieve data from various data sources such as
Collections, XML Docs, ADO.NET DataSet, web service, MS SQL Server, etc.
• It is integrated with C# or VB.NET and it eliminates the mismatch between different
programming languages and databases. It provides a single querying interface for
various data source types.
• An object will be returned as a result of LINQ query execution. It will allow you to
use an object-oriented approach on the result set and there is no need to worry
about the transformation of different result formats into objects.
10. How can you identify whether any changes are made to the DataSet object
since the time it was last loaded?

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.

11. What is the difference between Dataset.Clone() and DataSet.Copy() methods?

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

The methods provided by the DataRowCollection object are given below:

• Add()- It adds a newly created row into DataRowCollection.


• Remove()- It deletes the object DataRow from DataRowCollection.
• RemoveAt()- It deletes a row for which location is marked by an index number.
13. How to make SQL Server connection in ADO.NET?

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 (SqlConnection con = new SqlConnection(connectionString))


{
con.Open();
}

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:

Connection Has Been Successfully Established.


Press any key to continue...

On execution, if the connection has been established, a message will be displayed


on an output window.

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.

The code for serializing a DataSet is:

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;

public partial class Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
GridView gridView1=new GridView(); //Create GridView object
DataTable t = new DataTable("Employee"); // Create the table object
DataColumn c = new DataColumn(); //Creating table column
DataRow r; //Instance of row
c.ColumnName = "EmpID"; //Heading of the coloumn
c.DataType = Type.GetType("System.Int32"); //Set the data type of EmpID as an Integer
t.Columns.Add(c); //Adding a column to data table
c = new DataColumn();
c.ColumnName = "EmpName";
c.DataType = Type.GetType("System.String"); //Set the type of EmpName as String
t.Columns.Add(c);
for (int i = 0; i < 5; i++) //This code will create 5 rows
{
r = t.NewRow();
//Add Column values
r["EmpID"] = i;
r["EmpName"] = "Employee " + i;
t.Rows.Add(r);
}
gridView1.DataSource = t; //Set gridView1 Datasource as DataTable t
gridView1.DataBind(); //Bind Datasource to gridview
}
}

Output:

Conclusion

ADO.NET is a brilliant technology that was developed by Microsoft on the


framework of .NET. The primary role and responsibility of ADO.NET technology is
to setup a bridge between backend language and your database. A good experience
of this technology will be of great use from a development point of view.

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 Interview Questions


1. What is Pattern Matching in SQL?

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.

• Using the % wildcard to perform a simple search


The % wildcard matches zero or more characters of any type and can be used to
define wildcards both before and after the pattern. Search a student in your
database with first name beginning with the letter K:

SELECT *
FROM students
WHERE first_name LIKE 'K%'

• Omitting the patterns using the NOT keyword

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%'

• Matching a pattern anywhere using the % wildcard twice

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%'

• Using the _ wildcard to match pattern at a specific position

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%'

• Matching patterns for a specific length

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 -

SELECT * /* Matches first names with three or more letters */


FROM students
WHERE first_name LIKE '___%'

SELECT * /* Matches first names with exactly four characters */


FROM students
WHERE first_name LIKE '____'
2. How to create empty tables with the same structure as another table?

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.

SELECT * INTO Students_copy


FROM Students WHERE 1 = 2;
3. What is a Recursive Stored Procedure?

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.

DELIMITER $$ /* Set a new delimiter => $$ */


CREATE PROCEDURE calctotal( /* Create the procedure */
IN number INT, /* Set Input and Ouput variables */
OUT total INT
) BEGIN
DECLARE score INT DEFAULT NULL; /* Set the default value => "score" */
SELECT awards FROM achievements /* Update "score" via SELECT query */
WHERE id = number INTO score;
IF score IS NULL THEN SET total = 0; /* Termination condition */
ELSE
CALL calctotal(number+1); /* Recursive call */
SET total = total + score; /* Action after recursion */
END IF;
END $$ /* End of procedure */
DELIMITER ; /* Reset the delimiter */
You can download a PDF version of Sql Interview Questions.

Download PDF

4. What is a Stored Procedure?

A stored procedure is a subroutine available to applications that access a relational


database management system (RDBMS). Such procedures are stored in the
database data dictionary. The sole disadvantage of stored procedure is that it can be
executed nowhere except in the database and occupies more memory in the
database server. It also provides a sense of security and functionality as users who
can't access the data directly can be granted access via stored procedures.
DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM myDB.students;
END $$
DELIMITER ;

5. What is Collation? What are the different types of Collation Sensitivity?

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:

• Case sensitivity: A and a are treated differently.


• Accent sensitivity: a and á are treated differently.
• Kana sensitivity: Japanese kana characters Hiragana and Katakana are treated
differently.
• Width sensitivity: Same character represented in single-byte (half-width) and
double-byte (full-width) are treated differently.

6. What are the differences between OLTP and OLAP?

OLTP stands for Online Transaction Processing, is a class of software applications


capable of supporting transaction-oriented programs. An important attribute of an
OLTP system is its ability to maintain concurrency. OLTP systems often follow a
decentralized architecture to avoid single points of failure. These systems are
generally designed for a large audience of end-users who conduct short
transactions. Queries involved in such databases are generally simple, need fast
response times, and return relatively few records. A number of transactions per
second acts as an effective measure for such systems.

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?

OLTP stands for Online Transaction Processing, is a class of software applications


capable of supporting transaction-oriented programs. An essential attribute of an
OLTP system is its ability to maintain concurrency. To avoid single points of failure,
OLTP systems are often decentralized. These systems are usually designed for a
large number of users who conduct short transactions. Database queries are usually
simple, require sub-second response times, and return relatively few records. Here
is an insight into the working of an OLTP system [ Note - The figure is not important
for interviews ] -
Advance your career with Mock Assessments

Real-world coding challenges for top company interviews

Real-Life Problems

Detailed reports

Attempt Now

8. What is User-defined function? What are its various types?

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:

• Scalar Function: As explained earlier, user-defined scalar functions return a single


scalar value.
• Table-Valued Functions: User-defined table-valued functions return a table as
output.
o Inline: returns a table data type based on a single SELECT statement.
o Multi-statement: returns a tabular result-set but, unlike inline, multiple
SELECT statements can be used inside the function body.

9. What is a UNIQUE constraint?

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.

CREATE TABLE Students ( /* Create table with a single field as unique */


ID INT NOT NULL UNIQUE
Name VARCHAR(255)
);

CREATE TABLE Students ( /* Create table with multiple fields as unique */


ID INT NOT NULL
LastName VARCHAR(255)
FirstName VARCHAR(255) NOT NULL
CONSTRAINT PK_Student
UNIQUE (ID, FirstName)
);

ALTER TABLE Students /* Set a column as unique */


ADD UNIQUE (ID);
ALTER TABLE Students /* Set multiple columns as unique */
ADD CONSTRAINT PK_Student /* Naming a unique constraint */
UNIQUE (ID, FirstName);
10. What is a Query?

A query is a request for data or information from a database table or combination of


tables. A database query can be either a select query or an action query.

SELECT fname, lname /* select query */


FROM myDb.students
WHERE student_id = 1;
UPDATE myDB.students /* action query */
SET fname = 'Captain', lname = 'America'
WHERE student_id = 1;
11. What is Data Integrity?

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.

12. What is the difference between Clustered and Non-clustered index?

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.

Get Access to 250+ Guides with Scaler Mobile App!

Experience free learning content on the Scaler Mobile App

4.5

100K+

Play Store

13. What is an Index? Explain its different types.

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 and Non-Unique Index:

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.

CREATE UNIQUE INDEX myIndex


ON students (enroll_no);

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 and Non-Clustered Index:

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.

Write a SQL statement to create a UNIQUE INDEX "my_index" on "my_table" for


fields "column_1" & "column_2".

14. What is a Cross-Join?

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.

SELECT stu.name, sub.subject


FROM students AS stu
CROSS JOIN subjects AS sub;
Write a SQL statement to CROSS JOIN 'table_1' with 'table_2' and fetch 'col_1'
from table_1 & 'col_2' from table_2 respectively. Do not use alias.

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.

15. What is a Self-Join?

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.

SELECT A.emp_id AS "Emp_ID",A.emp_name AS "Employee",


B.emp_id AS "Sup_ID",B.emp_name AS "Supervisor"
FROM employee A, employee B
WHERE A.emp_sup = B.emp_id;
16. What is a Join? List its different types.

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?

A FOREIGN KEY comprises of single or collection of fields in a table that essentially


refers to the PRIMARY KEY in another table. Foreign key constraint ensures
referential integrity in the relation between two tables.
The table with the foreign key constraint is labeled as the child table, and the table
containing the candidate key is labeled as the referenced or parent table.

CREATE TABLE Students ( /* Create table with foreign key - Way 1 */


ID INT NOT NULL
Name VARCHAR(255)
LibraryID INT
PRIMARY KEY (ID)
FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
);

CREATE TABLE Students ( /* Create table with foreign key - Way 2 */


ID INT NOT NULL PRIMARY KEY
Name VARCHAR(255)
LibraryID INT FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
);

ALTER TABLE Students /* Add a new foreign key */


ADD FOREIGN KEY (LibraryID)
REFERENCES Library (LibraryID);

What type of integrity constraint does the foreign key ensure?

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:

SELECT name, email, mob, address


FROM myDb.contacts
WHERE roll_no IN (
SELECT roll_no
FROM myDb.students
WHERE subject = 'Maths');

There are two types of subquery - Correlated and Non-Correlated.

• A correlated subquery cannot be considered as an independent query, but it can


refer to the column in a table listed in the FROM of the main query.
• A non-correlated subquery can be considered as an independent query and the
output of the subquery is substituted in the main query.

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

19. What is a Primary Key?

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

ALTER TABLE Students /* Set a column as primary key */


ADD PRIMARY KEY (ID);
ALTER TABLE Students /* Set multiple columns as primary key */
ADD CONSTRAINT PK_Student /*Naming a Primary Key*/
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'.

20. What are Constraints in SQL?

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.

21. What are Tables and Fields?

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.

22. What is the difference between SQL and MySQL?

SQL is a standard language for retrieving and manipulating structured databases. On


the contrary, MySQL is a relational database management system, like SQL Server,
Oracle or IBM DB2, that is used to manage SQL databases.
23. What is SQL?

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.

24. What is RDBMS? How is it different from DBMS?

RDBMS stands for Relational Database Management System. The key


difference here, compared to DBMS, is that RDBMS stores data in the form of a
collection of tables, and relations can be defined between the common fields of
these tables. Most modern database management systems like MySQL, Microsoft
SQL Server, Oracle, IBM DB2, and Amazon Redshift are based on RDBMS.

25. What is DBMS?

DBMS stands for Database Management System. DBMS is a system software


responsible for the creation, retrieval, updation, and management of the database. It
ensures that our data is consistent, organized, and is easily accessible by serving as
an interface between the database and its end-users or application software.

26. What is Database?

A database is an organized collection of data, stored and retrieved digitally from a


remote or local computer system. Databases can be vast and complex, and such
databases are developed using fixed design and modeling approaches.
27. What is the SELECT statement?

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.

SELECT * FROM myDB.students;


28. What are some common clauses used with SELECT query in SQL?

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.

SELECT COUNT(studentId), country


FROM myDB.students
WHERE country != "INDIA"
GROUP BY country
HAVING COUNT(studentID) > 5;
29. What are UNION, MINUS and INTERSECT commands?

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

SELECT name FROM Students /* Fetch the union of queries */


UNION
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch the union of queries with duplicates*/
UNION ALL
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch names from students */
MINUS /* that aren't present in contacts */
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch names from students */
INTERSECT /* that are present in contacts as well */
SELECT name FROM Contacts;

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

30. What is Cursor? How to use a Cursor?

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.

Working with SQL Cursor:

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.

DECLARE @name VARCHAR(50) /* Declare All Required Variables */


DECLARE db_cursor CURSOR FOR /* Declare Cursor Name*/
SELECT name
FROM myDB.students
WHERE parent_name IN ('Sara', 'Ansh')
OPEN db_cursor /* Open cursor and Fetch data into @name */
FETCH next
FROM db_cursor
INTO @name
CLOSE db_cursor /* Close the cursor and deallocate the resources */
DEALLOCATE db_cursor
31. What are Entities and Relationships?

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.

Relationships: Relations or links between entities that have something to do with


each other. For example - The employee's table in a company's database can be
associated with the salary table in the same database.

32. List the different types of relationships in SQL.

• 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 a feature of SQL that is supported by most, if not all, RDBMSs. It is a


temporary name assigned to the table or table column for the purpose of a
particular SQL query. In addition, aliasing can be employed as an obfuscation
technique to secure the real names of database fields. A table alias is also called a
correlation name.

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.

SELECT A.emp_name AS "Employee" /* Alias using AS keyword */


B.emp_name AS "Supervisor"
FROM employee A, employee B /* Alias without AS keyword */
WHERE A.emp_sup = B.emp_id;

Write an SQL statement to select all from table "Limited" with alias "Ltd".

34. What is a View?

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?

Normalization represents the way of organizing structured data in the database


efficiently. It includes the creation of tables, establishing relationships between
them, and defining rules for those relationships. Inconsistency and redundancy can
be kept in check based on these rules, hence, adding flexibility to the database.

36. What is Denormalization?

Denormalization is the inverse process of normalization, where the normalized


schema is converted into a schema that has redundant information. The
performance is improved by using redundancy and keeping the redundant data
consistent. The reason for performing denormalization is the overheads produced in
the query processor by an over-normalized structure.

37. What are the various forms of Normalization?

Normal Forms are used to eliminate or reduce redundancy in database tables. The
different forms are as follows:

• First Normal Form:


A relation is in first normal form if every attribute in that relation is a single-valued
attribute. If a relation contains a composite or multi-valued attribute, it violates the
first normal form. Let's consider the following students table. Each student in the
table, has a name, his/her address, and the books they issued from the public library
-

Students Table

Student Address Books Issued Salutation

Amanora Park Town Until the Day I Die (Emily Carpenter), Inception
Sara Ms.
94 (Christopher Nolan)

The Alchemist (Paulo Coelho), Inferno (Dan


Ansh 62nd Sector A-10 Mr.
Brown)

24th Street Park Beautiful Bad (Annie Ward), Woman 99 (Greer


Sara Mrs.
Avenue Macallister)

Ansh Windsor Street 777 Dracula (Bram Stoker) Mr.

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 -

Students Table (1st Normal Form)


Student Address Books Issued Salutation

Sara Amanora Park Town 94 Until the Day I Die (Emily Carpenter) Ms.

Sara Amanora Park Town 94 Inception (Christopher Nolan) Ms.

Ansh 62nd Sector A-10 The Alchemist (Paulo Coelho) Mr.

Ansh 62nd Sector A-10 Inferno (Dan Brown) Mr.

Sara 24th Street Park Avenue Beautiful Bad (Annie Ward) Mrs.

Sara 24th Street Park Avenue Woman 99 (Greer Macallister) Mrs.

Ansh Windsor Street 777 Dracula (Bram Stoker) Mr.

• Second Normal Form:

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.

Students Table (2nd Normal Form)

Student_ID Student Address Salutation

1 Sara Amanora Park Town 94 Ms.

2 Ansh 62nd Sector A-10 Mr.

3 Sara 24th Street Park Avenue Mrs.

4 Ansh Windsor Street 777 Mr.

Books Table (2nd Normal Form)


Student_ID Book Issued

1 Until the Day I Die (Emily Carpenter)

1 Inception (Christopher Nolan)

2 The Alchemist (Paulo Coelho)

2 Inferno (Dan Brown)

3 Beautiful Bad (Annie Ward)

3 Woman 99 (Greer Macallister)

4 Dracula (Bram Stoker)

Example 2 - Consider the following dependencies in relation to R(W,X,Y,Z)

WX -> Y [W and X together determine Y]


XY -> Z [X and Y together determine Z]

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.

• Third Normal Form

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.

Students Table (3rd Normal Form)

Student_ID Student Address Salutation_ID

1 Sara Amanora Park Town 94 1

2 Ansh 62nd Sector A-10 2


Student_ID Student Address Salutation_ID

3 Sara 24th Street Park Avenue 3

4 Ansh Windsor Street 777 1

Books Table (3rd Normal Form)

Student_ID Book Issued

1 Until the Day I Die (Emily Carpenter)

1 Inception (Christopher Nolan)

2 The Alchemist (Paulo Coelho)

2 Inferno (Dan Brown)

3 Beautiful Bad (Annie Ward)

3 Woman 99 (Greer Macallister)

4 Dracula (Bram Stoker)

Salutations Table (3rd Normal Form)

Salutation_ID Salutation

1 Ms.

2 Mr.

3 Mrs.

Example 2 - Consider the following dependencies in relation to R(P,Q,R,S,T)

P -> QR [P together determine C]


RS -> T [B and C together determine D]
Q -> S
T -> P

For the above relation to exist in 3NF, all possible candidate keys in the above
relation should be {P, RS, QR, T}.

• Boyce-Codd Normal Form

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.

38. What are the TRUNCATE, DELETE and DROP statements?

DELETE statement is used to delete rows from a table.

DELETE FROM Candidates


WHERE CandidateId > 1000;

TRUNCATE command is used to delete all the rows from the table and free the
space containing the table.

TRUNCATE TABLE Candidates;

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.

DROP TABLE Candidates;

Write a SQL statement to wipe a table 'Temporary' from memory.

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.

39. What is the difference between DROP and TRUNCATE statements?

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.

41. What are Aggregate and Scalar functions?

An aggregate function performs operations on a collection of values to return a


single scalar value. Aggregate functions are often used with the GROUP BY and
HAVING clauses of the SELECT statement. Following are the widely used SQL
aggregate functions:

• AVG() - Calculates the mean of a collection of values.


• COUNT() - Counts the total number of records in a specific table or view.
• MIN() - Calculates the minimum of a collection of values.
• MAX() - Calculates the maximum of a collection of values.
• SUM() - Calculates the sum of a collection of values.
• FIRST() - Fetches the first element in a collection of values.
• LAST() - Fetches the last element in a collection of values.

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:

• LEN() - Calculates the total length of the given field (column).


• UCASE() - Converts a collection of string values to uppercase characters.
• LCASE() - Converts a collection of string values to lowercase characters.
• MID() - Extracts substrings from a collection of string values in a table.
• CONCAT() - Concatenates two or more strings.
• RAND() - Generates a random collection of numbers of a given length.
• ROUND() - Calculates the round-off integer value for a numeric field (or decimal
point values).
• NOW() - Returns the current date & time.
• FORMAT() - Sets the format to display a collection of values.

PostgreSQL Interview Questions


1. What is PostgreSQL?

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.

2. What is the capacity of a table in PostgreSQL?

The maximum size of PostgreSQL is 32TB.

3. What is the importance of the TRUNCATE statement?

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:

TRUNCATE TABLE name_of_table


RESTART IDENTITY;

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?

A token in PostgreSQL is either a keyword, identifier, literal, constant, quotes


identifier, or any symbol that has a distinctive personality. They may or may not be
separated using a space, newline or a tab. If the tokens are keywords, they are
usually commands with useful meanings. Tokens are known as building blocks of
any PostgreSQL code.

5. What are partitioned tables called 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:

• Range Partitioning: This method is done by partitioning based on a range of values.


This method is most commonly used upon date fields to get monthly, weekly or
yearly data. In the case of corner cases like value belonging to the end of the range,
for example: if the range of partition 1 is 10-20 and the range of partition 2 is 20-
30, and the given value is 10, then 10 belongs to the second partition and not the
first.
• List Partitioning: This method is used to partition based on a list of known values.
Most commonly used when we have a key with a categorical value. For example,
getting sales data based on regions divided as countries, cities, or states.
• Hash Partitioning: This method utilizes a hash function upon the partition key. This
is done when there are no specific requirements for data division and is used to
access data individually. For example, you want to access data based on a specific
product, then using hash partition would result in the dataset that we require.

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.

6. How can we start, restart and stop the PostgreSQL server?

• To start the PostgreSQL server, we run:

service postgresql start

• Once the server is successfully started, we get the below message:

Starting PostgreSQL: ok

• To restart the PostgreSQL server, we run:

service postgresql restart

Once the server is successfully restarted, we get the message:

Restarting PostgreSQL: server stopped


ok

• To stop the server, we run the command:

service postgresql stop

Once stopped successfully, we get the message:

Stopping PostgreSQL: server stopped


ok
7. What is the command used for creating a database in PostgreSQL?

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:

ALTER TABLE tname


ALTER COLUMN col_name [SET DATA] TYPE new_data_type;
9. How do you define Indexes in PostgreSQL?

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.

Select * from some_table where table_col=120


10. Define sequence.

A sequence is a schema-bound, user-defined object which aids to generate a


sequence of integers. This is most commonly used to generate values to identity
columns in a table. We can create a sequence by using the CREATE
SEQUENCE statement as shown below:

CREATE SEQUENCE serial_num START 100;

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:

INSERT INTO ib_table_name VALUES (nextval('serial_num'), 'interviewbit');


11. What are string constants in PostgreSQL?

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.

12. How can you get a list of all databases in PostgreSQL?

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:

DROP DATABASE database_name;

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.

• Atomicity: This property ensures that the transaction is completed in all-or-nothing


way.
• Consistency: This ensures that updates made to the database is valid and follows
rules and restrictions.
• Isolation: This property ensures integrity of transaction that are visible to all other
transactions.
• Durability: This property ensures that the committed transactions are stored
permanently in the database.

PostgreSQL is compliant with ACID properties.

15. Can you explain the architecture of PostgreSQL?

• The architecture of PostgreSQL follows the client-server model.


• The server side comprises of background process manager, query processer, utilities
and shared memory space which work together to build PostgreSQL’s instance that
has access to the data. The client application does the task of connecting to this
instance and requests data processing to the services. The client can either be GUI
(Graphical User Interface) or a web application. The most commonly used client for
PostgreSQL is pgAdmin.
16. What do you understand by multi-version concurrency control?

MVCC or Multi-version concurrency control is used for avoiding unnecessary


database locks when 2 or more requests tries to access or modify the data at the
same time. This ensures that the time lag for a user to log in to the database is
avoided. The transactions are recorded when anyone tries to access the content.

For more information regarding this, you can refer here.

17. What do you understand by command enable-debug?

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.

• Dirty reads: If a transaction reads data that is written due to concurrent


uncommitted transaction, these reads are called dirty reads.
• Phantom reads: This occurs when two same queries when executed separately
return different rows. For example, if transaction A retrieves some set of rows
matching search criteria. Assume another transaction B retrieves new rows in
addition to the rows obtained earlier for the same search criteria. The results are
different.
• Non-repeatable reads: This occurs when a transaction tries to read the same row
multiple times and gets different values each time due to concurrency. This happens
when another transaction updates that data and our current transaction fetches that
updated data, resulting in different values.

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

Read Uncommitted Might occur Might occur Might occur

Read Committed Won’t occur Might occur Might occur

Repeatable Read Won’t occur Might occur Won’t occur

Serializable Won’t occur Won’t occur Won’t occur

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.

For more information, you can refer here.

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.

21. How do you perform case-insensitive searches using regular expressions in


PostgreSQL?

To perform case insensitive matches using a regular expression, we can use


POSIX (~*) expression from pattern matching operators. For example:

'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 1: Navigate to the bin folder of the PostgreSQL installation path.

C:\>cd C:\Program Files\PostgreSQL\10.0\bin

Step 2: Execute pg_dump program to take the dump of data to a .tar folder as
shown below:

pg_dump -U postgres -W -F t sample_data > C:\Users\admin\pgbackup\sample_data.tar


The database dump will be stored in the sample_data.tar file on the location
specified.

23. Does PostgreSQL support full text search?

Full-Text Search is the method of searching single or collection of documents stored


on a computer in a full-text based database. This is mostly supported in advanced
database systems like SOLR or ElasticSearch. However, the feature is present but is
pretty basic in PostgreSQL.

24. What are parallel queries in PostgreSQL?

Parallel Queries support is a feature provided in PostgreSQL for devising query


plans capable of exploiting multiple CPU processors to execute the queries faster.

25. Differentiate between commit and checkpoint.

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.

PostgreSQL being an open-source database system having extremely robust and


sophisticated ACID, Indexing, and Transaction supports has found widespread
popularity among the developer community.
SQL Interview Preparation – Theory + Query Based Questions with Answers

------------------------------------------------------------
BASIC SQL QUESTIONS
------------------------------------------------------------
1. What is SQL?
SQL (Structured Query Language) is used to communicate with databases for
storing, retrieving, and manipulating data.

2. What are DDL, DML, DCL, and TCL commands?


- DDL (Data Definition Language): CREATE, ALTER, DROP
- DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE
- DCL (Data Control Language): GRANT, REVOKE
- TCL (Transaction Control Language): COMMIT, ROLLBACK, SAVEPOINT

3. Difference between DELETE, TRUNCATE, DROP?


DELETE: Removes selected rows, can be rolled back.
TRUNCATE: Removes all rows, faster, cannot be rolled back.
DROP: Deletes the entire table structure.

4. What is a primary key?


Uniquely identifies each row in a table. Only one primary key per table.

5. What is a foreign key?


A field in one table that refers to the primary key in another.

6. What is a unique key?


Ensures all values in a column are different.

7. What is a NULL value?


Represents missing or unknown value. Not equal to 0 or empty string.

------------------------------------------------------------
NORMALIZATION
------------------------------------------------------------
1. What is normalization?
The process of organizing data to minimize redundancy.

2. Explain Normal Forms:


- 1NF: Remove repeating groups.
- 2NF: Remove partial dependencies.
- 3NF: Remove transitive dependencies.
- BCNF: Stronger version of 3NF.

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

2. Dept-wise max salary:


SELECT DeptId, MAX(Salary) FROM Employees GROUP BY DeptId;

3. Find duplicate rows:


SELECT Name, COUNT(*) FROM Employees GROUP BY Name HAVING COUNT(*) > 1;

4. Delete duplicate rows:


WITH CTE AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY Name ORDER BY ID) AS rn
FROM Employees
)
DELETE FROM CTE WHERE rn > 1;

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;

2. Employees with no department:


SELECT * FROM Employees E
LEFT JOIN Departments D ON E.DeptId = D.DeptId
WHERE D.DeptId IS NULL;

3. Employees joined in last 30 days:


SELECT * FROM Employees
WHERE JoinDate >= DATEADD(DAY, -30, GETDATE());

4. Count of employees per department:


SELECT DeptId, COUNT(*) FROM Employees GROUP BY DeptId;

5. Highest salary with employee name:


SELECT Name, Salary FROM Employees
WHERE Salary = (SELECT MAX(Salary) FROM Employees);
Self Introduction - Infosys Technical Interview

Good morning/afternoon, my name is Kumar Mrinal. I am from Muzaffarpur, Bihar, India.

I completed my schooling at Pristine Children's High School in Muzaffarpur, where I built a strong

foundation in academics. After that, I pursued my Bachelor of Engineering in Computer Science

from R.L. Jalappa Institute of Technology, Bangalore.

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

built using .NET Core, following a three-tier architecture.

My key responsibilities include:

- Developing REST APIs using ASP.NET Core

- Working closely with SQL Server for database operations

- 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,

working on client requirements, and applying agile methodologies in the team.

I am really excited about this opportunity with Infosys, as I believe it will allow me to take on more

challenging roles and grow further in my career as a software engineer.

Q: Why do you want to leave HCL and join Infosys?

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

innovation, global client base, and strong career development framework.

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.

Q: Tell me about a challenge you faced in your project?

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.

Q: What is your biggest strength?

My biggest strength is problem-solving and staying calm under pressure. I analyze issues

systematically and work collaboratively to resolve them efficiently.

Q: What is your biggest weakness?

One area I am working on is public speaking. While I communicate well within teams, I have started

taking small sessions to improve my presentation skills.

Q: Where do you see yourself in 5 years?

In 5 years, I see myself as a senior software engineer or technical lead, contributing to end-to-end

solutions, mentoring juniors, and being actively involved in architecture-level decisions.


Sales HR Tracking Project - .NET Core Interview Q&A

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.

1. What was the purpose of the Sales HR Tracking System?

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.

2. What modules did you work on?

I mainly worked on backend modules like attendance tracking, leave workflows, role-based access, and sales

target assignment APIs.

3. Can you describe the architecture of your application?

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.

4. What was your role in the project?

I focused on backend development, building REST APIs, implementing business logic, and managing

database operations using stored procedures.

5. How did you create APIs in .NET Core?

I used ASP.NET Core Web API controllers with routing and proper data validation annotations to handle

CRUD operations.

6. How did you implement authentication and authorization?

JWT (JSON Web Tokens) were used for authentication and role-based authorization was implemented using

[Authorize(Roles = "Admin")] attributes.

7. What is JWT and how did you use it?

JWT is a token-based stateless authentication mechanism. After login, a token is generated and sent with
each request for authorization.

8. How did you secure your APIs?

APIs were protected using HTTPS, JWT authentication, and input validation. CORS policies were configured

to only allow known frontend origins.

9. How did you interact with the database?

I used ADO.NET and stored procedures for DB access, focusing on performance and secure data

transactions.

10. Did you use raw SQL or stored procedures?

Yes, I used stored procedures for all database operations to improve performance and control business logic

at the database level.

11. How did you handle transactions?

I used SQL transactions with stored procedures and managed connection and command execution within

try-catch blocks in .NET.

12. How did you improve API performance?

By using asynchronous operations, optimizing stored procedures, and caching static data where necessary.

13. Did you use async/await?

Yes, I used async methods in .NET Core for all I/O-bound operations to improve scalability.

14. How did you protect sensitive data?

Salary and other sensitive data were secured using HTTPS and access restrictions based on user roles.

15. How did you prevent SQL Injection and XSS?

SQL Injection was prevented through parameterized commands in ADO.NET and stored procedures. XSS

was mitigated through input validation.

16. How was the application deployed?

It was deployed using IIS with automated build and release pipelines through Azure DevOps.

17. How did you manage logs and monitoring?


Logging was handled using Serilog, writing to files and integrating with centralized monitoring tools like Seq.

18. How did the frontend integrate with the backend?

React used Fetch API to call .NET Core APIs. I ensured endpoints returned standardized responses and

configured CORS accordingly.

19. Did you write any React code?

Only minor adjustments during integration testing. My main role was focused on .NET Core development.

You might also like