
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Interview Questions Answers &#8211; CodeInDotNet</title>
	<atom:link href="https://www.codeindotnet.com/category/interview-questions-answers/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codeindotnet.com</link>
	<description>C# Dot Net Programming tutorial &#38; code examples</description>
	<lastBuildDate>Thu, 28 Nov 2024 13:30:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://www.codeindotnet.com/wp-content/uploads/2021/04/SiteIcon.png</url>
	<title>Interview Questions Answers &#8211; CodeInDotNet</title>
	<link>https://www.codeindotnet.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Top 80+ Entity Framework Interview Questions and Answers</title>
		<link>https://www.codeindotnet.com/entity-framework-interview-questions-answers/</link>
					<comments>https://www.codeindotnet.com/entity-framework-interview-questions-answers/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 10 Nov 2024 14:37:10 +0000</pubDate>
				<category><![CDATA[Interview Questions Answers]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=10188</guid>

					<description><![CDATA[Here are the top 80+ Entity Framework interview questions and answers for beginners and professionals. Other Interview Questions &#8211; OOPs, C#, SQL, Web API Share to Whatsapp Basic Entity Framework Interview Questions &#38; Answers Download all Questions as .PDF Search: Clear × What is Entity Framework? Entity Framework (EF) is an ORM (Object-Relational Mapper) for [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/qa/entity-framework-interview-questions-answers-csharp.jpg" alt=""/></figure>



<p class="p-mb-0">Here are the top 80+ Entity Framework interview questions and answers for beginners and professionals. </p>



<p class="has-text-align-right pt5"><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"><strong>Other Interview Questions &#8211;</strong></mark> <a href="/oops-interview-questions-answers/" data-type="post" data-id="7894"><strong>OOPs</strong></a>, <strong><a href="/csharp-interview-questions-answers/" data-type="post" data-id="8095">C#</a></strong>, <strong><a href="/sql-interview-questions-answers/" data-type="post" data-id="7407">SQL</a>, <strong><a href="/web-api-interview-questions-answers/" data-type="post" data-id="7407">Web API</a></strong></strong></p>



<div style="text-align: right;"><a href="https://api.whatsapp.com/send?text=Entity Framework Interview Questions and Answers - https://www.codeindotnet.com/entity-framework-interview-questions-answers/" rel="nofollow noopener" target="_blank" style="font-size: 18px; color: #fff; background-color: #03a941; border-radius: 5px; padding: 7px 10px;">
<span style="font-size: 22px;"><i class="fa fa-whatsapp"></i></span>
<span>Share to Whatsapp</span> </a>
</div>
<br><br>



<h2 class="wp-block-heading h2Cust1"><strong>Basic Entity Framework Interview Questions &amp; Answers</strong></h2>



<p class="has-text-align-right pt5"><strong><a href="#download-questions" data-type="internal" data-id="#download-questions">Download all Questions as .PDF</a></strong></p>



<div id="searchPopup">
	<div class="popup-header">			
		<span style="font-weight:bold;">Search: </span>
		<input type="text" id="myInput" autocomplete="off" placeholder=" type keyword(s) &amp; filter Questions..." onclick="document.getElementById('myList').style.display = 'block'; document.getElementById('btnpopclose').style.display = 'block';">
		<button onclick="displayAllResult();" style="padding: 5px 9px; border-radius: 10px; color:#fff;" >Clear</button>
		<button id="btnpopclose" class="popup-close" onclick="document.getElementById('myList').style.display = 'none'; document.getElementById('btnpopclose').style.display = 'none';">×</button>
	</div>
	<div id="myList"></div>		
</div>



<style>
.popup-close {
    font-size: 1.25rem;
    font-weight: 700;
    padding: .3125rem .625rem;
    border-radius: .3125rem;
    background-color: red;
    color: #fff;
    border: none;
    float: right;
    display: none;
    /*margin: -.3125rem;*/
}

#myInput{
width: calc(100% - 11.5625rem);
display:inline; 
border-radius: 10px; 
margin:0;
}


#searchPopup{
border: 1px solid #6a409759;
    padding: 10px;
    border-radius: 5px;
}

#myList{
line-height: 1.7; 
font-size: 16px; 
overflow-y: scroll; 
height: 250px; 
/*border-bottom: 3px lightgray solid;*/
display:none; 
margin-top: 15px;
}
</style>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">Entity Framework (EF) is an ORM (Object-Relational Mapper) for .NET. It allows you to interact with databases using C# code, instead of writing SQL queries.</p>



<p class="custp1 p-mb-0"><strong>Example:</strong><br>If you have a Product class, EF can automatically create a table for it in the database and handle operations like adding, updating, or retrieving products without writing SQL code.</p>



<button class="shbtn" id="shbtn75640" onclick="showHideBlock(75640)">&#9660; <u>Show example</u></button>
<div id="shdiv75640" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    <span class="key">public</span> <span class="key">int</span> Id { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> <span class="key">decimal</span> Price { get; set; }
} </code></pre>
<br>

You can save data like this:

<pre class="pchl"><code><span class="key">using</span> (<span class="key">var</span> context = <span class="key">new</span> AppDbContext())
{
    <span class="key">var</span> product = <span class="key">new</span> Product { Name = <span class="str">"Laptop"</span>, Price = 1200.00M };
    context.Products.Add(product);
    context.SaveChanges();
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the main advantages of using Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">The main advantages of using Entity Framework are:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Reduces SQL Code</strong>: Allows developers to focus on C# code without manually writing SQL.</li>



<li><strong>Automates Database Operations</strong>: Handles CRUD operations automatically.</li>



<li><strong>Simplifies Data Access</strong>: Provides an easier way to interact with databases using LINQ.</li>



<li><strong>Change Tracking</strong>: Tracks object changes and updates the database accordingly.</li>



<li><strong>Migration Support</strong>: Manages database schema changes with migrations.</li>



<li><strong>Cross-Database Compatibility</strong>: Supports multiple database providers, like SQL Server, MySQL, and PostgreSQL.</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Explain the difference between Database-First, Model-First, and Code-First approaches.</strong></h3>



<p class="pt20 p-mb-0">The three approaches in Entity Framework are:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Database-First</strong>: The database is created first, and then EF generates classes based on the existing database schema. <br><strong><em>example:</em></strong> You have a database with tables, and EF generates C# models like &#8216;Customer&#8217; and &#8216;Order&#8217; from it.</li>



<li class="custp1"><strong>Model-First</strong>: You create a visual model using a designer, and EF generates the database and code based on that model. <br><strong><em>example:</em></strong> You use a diagram to design entities and relationships, then EF creates both the database tables and C# classes.</li>



<li class="custp1"><strong>Code-First</strong>: You write the C# classes first, and EF generates the database schema based on those classes. <br><strong><em>example:</em></strong> You create a &#8216;Product&#8217; class in C#, and EF automatically generates the corresponding database table.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a DbContext in Entity Framework?</strong></h3>



<p class="pt20">DbContext is the primary class for interacting with the database. It acts as a bridge between application and the database, managing the retrieval and saving of data.</p>



<p class="p-mb-0"><strong>Key responsibilities:</strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>Managing database connections</li>



<li>Tracking changes to entities</li>



<li>Executing queries and saving data</li>
</ul>



<br>



<p class="p-mb-0">In simple terms, it&#8217;s the class you use to query and save data to the database.</p>



<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">class</span> AppDbContext : <span style="background:#f2f19d;">DbContext</span>
{
    <span class="key">public</span> DbSet&lt;Product&gt Products { get; set; }
} </code></pre>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the DbContextOptions class?</strong></h3>



<p class="pt20 p-mb-0">The <strong>DbContextOptions</strong> class is used to configure how a <strong>DbContext</strong> should behave and interact with the database. It holds configuration options such as the database provider (SQL Server/ MySQL),  connection string, logging &amp; diagnostics, Other Options (like lazy loading, query tracking, and caching) and it passes these options to the <span class="spanHT">DbContext</span>.</p>



<button class="shbtn" id="shbtn4591" onclick="showHideBlock(4591)">&#9660; <u>Show example</u></button>
<div id="shdiv4591" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>AppDbContext.cs</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> AppDbContext : DbContext
{
    <span class="key">public</span> AppDbContext(<span style="background:#f2f19d;">DbContextOption</span>s&lt;AppDbContext&gt options) : <span class="key">base</span>(options) { }

    <span class="key">public</span> DbSet&lt;Product&gt Products { get; set; }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>In Startup.cs, you configure the DbContextOptions like this:</b></div>
<pre class="pchl"><code><span class="key">var</span> optionsBuilder = <span class="key">new</span> <b>DbContextOptionsBuilder</b>&lt;AppDbContext&gt();
optionsBuilder.UseSqlServer(<span class="str">"YourConnectionString"</span>);

<span class="com">// Passing options to the DbContext</span>
<span class="key">using</span> (<span class="key">var</span> context = <span class="key">new</span> AppDbContext(optionsBuilder.Options))
{
    <span class="com">// Your database operations here</span>
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a DbSet in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">A DbSet represents a collection of entities that you can query from and save to the database. It corresponds to a table in the database, and each entity in the DbSet is a row in that table. </p>



<p class="custp1 p-mb-0">For example, if you have a <strong>DbSet&lt;Product&gt;</strong>, it represents the <strong>Products</strong> table in the database.</p>



<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">class</span> AppDbContext : DbContext
{
    <span class="key">public</span> <span style="background:#f2f19d;">DbSet&lt;Product&gt</span> Products { get; set; } <span class="com">// Products table</span>
} </code></pre>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you define a primary key in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">There are two way to define a Primary Key:</p>



<p class="custp1 p-mb-0"><strong>1.</strong> The Primary key is usually defined by creating a property named <span class="spanHT">Id</span> or <span class="spanHT">&lt;ClassName&gt;Id</span> in the entity class. EF will automatically treat this as the primary key.</p>



<button class="shbtn" id="shbtn82259" onclick="showHideBlock(82259)">&#9660; <u>Show example</u></button>
<div id="shdiv82259" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    <span class="key">public</span> <span class="key">int</span> <span style="background:#f2f19d;">Id</span> { get; set; } <span class="com">// Primary Key</span>
    <span class="com">//or</span>
    <span class="com">public int <span style="background:#f2f19d;">ProductId</span> { get; set; } <span class="com">// Primary Key</span>

    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> <span class="key">decimal</span> Price { get; set; }
} </code></pre>

</div>
<br><br>



<p class="p-mb-0"><strong>2.</strong> If you want to explicitly define the primary key, you can use the <span class="spanHT">[Key]</span> attribute.</p>



<button class="shbtn" id="shbtn36964" onclick="showHideBlock(36964)">&#9660; <u>Show example</u></button>
<div id="shdiv36964" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    <span style="background:#f2f19d;">[Key]</span>
    <span class="key">public</span> <span class="key">int</span> ProductId { get; set; } <span class="com">// Primary Key</span>
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How can you configure a one-to-many relationship in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">A one-to-many relationship is configured by having one entity reference another entity (one side), and the other entity hold a collection of the first entity (many side). </p>



<p class="custp1 p-mb-0"><strong>Example</strong>: A <span class="spanHT">Category</span> can have many <span class="spanHT">Products</span>, but each <span class="spanHT">Product</span> belongs to one <span class="spanHT">Category</span>.</p>



<button class="shbtn" id="shbtn30739" onclick="showHideBlock(30739)">&#9660; <u>Show example</u></button>
<div id="shdiv30739" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Category
{
    <span class="key">public</span> <span class="key">int</span> CategoryId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span class="com">// One-to-Many: A Category has many Products</span>
    <span class="key">public</span> <span style="background:#f2f19d;">List&lt;Product&gt</span> Products { get; set; } 
}

<span class="key">public</span> <span class="key">class</span> <span style="background:#f2f19d;">Product</span>
{
    <span class="key">public</span> <span class="key">int</span> ProductId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span class="com">// Foreign Key: Product belongs to one Category</span>
    <span class="key">public</span> <span class="key">int</span> CategoryId { get; set; }
    <span class="key">public</span> Category Category { get; set; }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the OnModelCreating method in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">The OnModelCreating method in Entity Framework is used to configure the model and relationships between entities when the database is being created. It allows you to customize entity configurations that cannot be done through attributes. </p>



<p class="custp1 p-mb-0">It helps in fine-tuning how the entities are mapped to the database.</p>



<p class="custp1 p-mb-0"><strong>Common uses: </strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>Defining relationships (one-to-many, many-to-many)</li>



<li>Setting up database schema rules (table names, column properties)</li>



<li>Configuring keys, indexes, and constraints</li>
</ul>



<button class="shbtn" id="shbtn76956" onclick="showHideBlock(76956)">&#9660; <u>Show example</u></button>
<div id="shdiv76956" style="display: none;">

<pre class="pchl"><code><span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> <span style="background:#f2f19d;">OnModelCreating</span>(ModelBuilder modelBuilder)
{
    <span class="com">// Example: Configuring a one-to-many relationship</span>
    modelBuilder.Entity&lt;Product&gt()
        .HasOne(p =&gt p.Category)
        .WithMany(c =&gt c.Products)
        .HasForeignKey(p =&gt p.CategoryId);
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Lazy Loading in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0"><strong>Lazy Loading</strong> in Entity Framework is a feature where related data is loaded from the database only when it is accessed for the first time, rather than loading it upfront with the main entity.</p>



<p class="custp1 p-mb-0">This helps improve performance by fetching data only when needed.</p>



<p class="custp1 p-mb-0">For example, if you load a &#8216;Product&#8217; without accessing its related &#8216;Category&#8217;, the &#8216;Category&#8217; data will not be loaded until you explicitly access it.</p>



<p class="custp1 p-mb-0">Lazy Loading can be enabled by making navigation properties <span class="spanHT">virtual</span></p>



<button class="shbtn" id="shbtn89345" onclick="showHideBlock(89345)">&#9660; <u>Show example</u></button>
<div id="shdiv89345" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    <span class="key">public</span> <span class="key">int</span> ProductId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span class="com">// Lazy Loading: Related data is loaded only when accessed</span>
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">virtual</span> Category Category { get; set; }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Eager Loading in Entity Framework?<br>What is the purpose of the Include method in EF?</strong></h3>



<p class="pt20 p-mb-0"><strong>Eager Loading</strong> or <span class="spanHT">Include()</span> method is a technique where related data is loaded from the database along with the main entity, in a single query. This is done to avoid multiple round-trips to the database. </p>



<p class="custp1 p-mb-0">By default, Entity Framework uses <strong>lazy loading</strong>, meaning related entities are only loaded when accessed.</p>



<p class="custp1 p-mb-0">Use the <span class="spanHT">Include()</span> method to specify which related data to load.</p>



<button class="shbtn" id="shbtn81071" onclick="showHideBlock(81071)">&#9660; <u>Show example</u></button>
<div id="shdiv81071" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;">In this example, both Product and its related Category are loaded together in one database query.</div>

<pre class="pchl"><code><span class="key">var</span> products = context.Products
                      <span style="background:#f2f19d;">.Include</span>(p =&gt p.Category) <span class="com">// Eagerly loads related Category</span>
                      .ToList(); </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Explicit Loading in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0"><strong>Explicit Loading</strong> is a technique where you manually load related data after the main entity is already retrieved. It gives you full control over when to load the related data.</p>



<p class="custp1 p-mb-0">Unlike lazy loading, explicit loading doesn&#8217;t automatically load related data. You must explicitly tell Entity Framework to load it using the <span class="spanHT">Load()</span> method.</p>



<button class="shbtn" id="shbtn16114" onclick="showHideBlock(16114)">&#9660; <u>Show example</u></button>
<div id="shdiv16114" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;">In this case, the &#39;Product&#39; is retrieved first, and the related &#39;Category&#39; is loaded only when explicitly requested. The keyword used is &#39;Load()&#39;.</div>

<pre class="pchl"><code><span class="key">var</span> product = context.Products.First(p =&gt p.ProductId == 1);

<span class="com">// Manually load the related Category</span>
context.Entry(product)
       .Reference(p =&gt p.Category) <span class="com">// For a reference property</span>
       <span style="background:#f2f19d;">.Load()</span>; </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How does Entity Framework differ from ADO.NET?</strong></h3>



<br>
<table><thead><tr><th>Feature</th><th>Entity Framework (EF)</th><th>ADO.NET</th></tr></thead><tbody><tr><td><strong>Abstraction Level</strong></td><td>Higher-level ORM (Object-Relational Mapper)</td><td>Lower-level data access technology</td></tr><tr><td><strong>Data Access</strong></td><td>Uses C# objects to interact with the database</td><td>Requires manual SQL queries and commands</td></tr><tr><td><strong>Development Speed</strong></td><td>Faster, as it reduces the need to write SQL</td><td>Slower, due to manual handling of SQL and data</td></tr><tr><td><strong>Query Language</strong></td><td>Uses LINQ (Language Integrated Query)</td><td>Uses raw SQL queries or stored procedures</td></tr><tr><td><strong>Change Tracking</strong></td><td>Automatically tracks changes in entities</td><td>Requires manual handling of updates</td></tr><tr><td><strong>Database Handling</strong></td><td>Automated database schema generation and migrations</td><td>Manual management of database schema</td></tr><tr><td><strong>Complexity</strong></td><td>Easier to use, less boilerplate code</td><td>More complex, with greater control</td></tr><tr><td><strong>Best Suited For</strong></td><td>Rapid development and simpler CRUD operations</td><td>Scenarios requiring fine-grained control over data operations</td></tr></tbody></table>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Navigation Properties in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0"><strong>Navigation Properties</strong> allows you to navigate and manage relationships between entities. They represent the associations between different entities (like one-to-many or many-to-many relationships) and enable easy access to related data.</p>



<p class="custp1 p-mb-0">For example: In a <strong>one-to-many</strong> relationship, a &#8216;Category&#8217; can have multiple &#8216;Products&#8217;, and a &#8216;Product&#8217; can belong to one &#8216;Category&#8217;.</p>



<button class="shbtn" id="shbtn18374" onclick="showHideBlock(18374)">&#9660; <u>Show example</u></button>
<div id="shdiv18374" style="display: none;" class="shdt">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Category
{
    <span class="key">public</span> <span class="key">int</span> CategoryId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span class="com">// Navigation Property (One-to-Many)</span>
    <span class="key">public</span> List&lt;Product&gt Products { get; set; } 
}

<span class="key">public</span> <span class="key">class</span> Product
{
    <span class="key">public</span> <span class="key">int</span> ProductId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span class="com">// Navigation Property (Many-to-One)</span>
    <span class="key">public</span> Category Category { get; set; }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">In this example:</div>
<ul class="ol1 ol1-mb-0">
<li class="pt5">Products is a navigation property that allows the Category to access its related Product entities.</li>
<li>Category is a navigation property that allows the Product to access its related Category.</li>
</ul>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you configure a many-to-many relationship in Entity Framework?</strong></h3>



<p class="custp1 p-mb-0">You can configure a many-to-many relationship by simply using navigation properties in both entities. EF Core automatically creates the join table and you need not to explicitly configure anything unless you want to customize it.</p>



<button class="shbtn" id="shbtn27276" onclick="showHideBlock(27276)">&#9660; <u>Show example</u></button>
<div id="shdiv27276" style="display: none;" class="shdt">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Student
{
    <span class="key">public</span> <span class="key">int</span> StudentId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span class="com">// Navigation property for the many-to-many relationship</span>
    <span class="key">public</span> List&lt;Course&gt Courses { get; set; }
}

<span class="key">public</span> <span class="key">class</span> Course
{
    <span class="key">public</span> <span class="key">int</span> CourseId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Title { get; set; }

    <span class="com">// Navigation property for the many-to-many relationship</span>
    <span class="key">public</span> List&lt;Student&gt Students { get; set; }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;">In DbContext, the relationship can be implicitly defined without additional configuration:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> SchoolContext : DbContext
{
    <span class="key">public</span> DbSet&lt;Student&gt Students { get; set; }
    <span class="key">public</span> DbSet&lt;Course&gt Courses { get; set; }

    <span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&lt;Student&gt()
            .HasMany(s =&gt s.Courses)
            .WithMany(c =&gt c.Students);
    }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">This creates the many-to-many relationship with an automatic join table like StudentCourses without needing an explicit class.</div>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How can you enable and disable Lazy Loading in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">You can enable or disable <strong>Lazy Loading</strong> at both the <strong>context level</strong> and <strong>property level</strong>.</p>



<ol class="ol1 ol1-mb-0">
<li class="custp1"><b>At Context Level:</b> Lazy loading is <b><i>disabled by default</i></b>, you can <b><i>enable it</i></b> by calling <span class="spanHT">UseLazyLoadingProxies()</span> in Startup.cs
<br>
<button class="shbtnlist" id="shbtn80441" onclick="showHideBlock(80441)">&#9660; <u>Show example</u></button>
<div id="shdiv80441" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> AppDbContext : DbContext
{
    <span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.<span style="background:#f2f19d;">UseLazyLoadingProxies()</span>; <span class="com">// Enable Lazy Loading</span>
    }
} </code></pre>

</div>
</li>


<li class="custp1"><b>At the Property Level:</b> 
 <ul class="ol1 ol1-mb-0">
 <li><b>Enabling:</b> Mark navigation properties as <span class="spanHT">virtual</span> to allow EF to override them with proxies for lazy loading.
<br>
<button class="shbtnlist" id="shbtn39675" onclick="showHideBlock(39675)">&#9660; <u>Show example</u></button>
<div id="shdiv39675" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    <span class="key">public</span> <span class="key">int</span> ProductId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span class="key">public</span> <span class="key">int</span> CategoryId { get; set; }

    <span class="com">// Enable lazy loading for this navigation property</span>
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">virtual</span> Category Category { get; set; } 
} </code></pre>
</div>
 </li>
 <li class="custp1"><b>Disabling:</b> Do not mark the navigation property as <span class="spanHT">virtual</span> if you want to disable lazy loading for a specific property.
<br>
<button class="shbtnlist" id="shbtn70628" onclick="showHideBlock(70628)">&#9660; <u>Show example</u></button>
<div id="shdiv70628" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    <span class="key">public</span> <span class="key">int</span> ProductId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span class="key">public</span> <span class="key">int</span> CategoryId { get; set; }

    <span class="com">// Disable lazy loading by omitting 'virtual'</span>
    <span class="key">public</span> Category Category { get; set; } 
} </code></pre>
</div>
 </li>
 </ul>
</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Data Annotations in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0"><strong>Data Annotations</strong> in Entity Framework are attributes you can apply to your model classes and properties to configure how they should be mapped to the database. These annotations allow you to control things like validation, relationships, and schema details directly within the code, without needing to configure these settings in the DbContext.</p>



<button class="shbtn" id="shbtn2584" onclick="showHideBlock(2584)">&#9660; <u>Show example</u></button>
<div id="shdiv2584" style="display: none;">

<pre class="pchl"><code><span style="background:#f2f19d;">[Table(<span class="str">"Products"</span>)]</span>
<span class="key">public</span> <span class="key">class</span> Product
{
    <span style="background:#f2f19d;">[Key]</span>
    <span class="key">public</span> <span class="key">int</span> ProductId { get; set; }
	
    <span style="background:#f2f19d;">[Column(<span class="str">"Product_Name"</span>)]</span>
    [Required]
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
	
    <span style="background:#f2f19d;">[MaxLength(100)]</span>
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
	
    <span style="background:#f2f19d;">[StringLength(100, MinimumLength = 5)]</span>
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
	
    <span class="key">public</span> <span class="key">int</span> CategoryId { get; set; }

    <span style="background:#f2f19d;">[ForeignKey(<span class="str">"CategoryId"</span>)]</span>
    <span class="key">public</span> Category Category { get; set; }
	
    <span style="background:#f2f19d;">[ConcurrencyCheck]</span>
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
	
    <span style="background:#f2f19d;">[Timestamp]</span>
    <span class="key">public</span> byte[] RowVersion { get; set; }	
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle concurrency in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">Concurrency conflicts occur when multiple users try to update the same data at the same time. To handle these conflicts, you can use <strong>optimistic concurrency control</strong>. Entity Framework provides mechanisms to detect and resolve these conflicts using <strong>Concurrency Tokens</strong>.</p>



<p class="custp1 p-mb-0"><strong>Ways to Handle Concurrency in Entity Framework:</strong> </p>



<p class="custp1 p-mb-0"><strong>1. Using a Timestamp/RowVersion Column:</strong></p>



<p class="pt5 p-mb-0 p-lp-15">A common approach is to add a <span class="spanHT">Timestamp</span> or <span class="spanHT">RowVersion</span> column to the entity. This column gets updated every time the record is modified, allowing Entity Framework to detect if someone else has updated the record between the time it was read and when an update is attempted.</p>



<button class="shbtn" id="shbtn38748" onclick="showHideBlock(38748)" style="margin-left: 15px;">&#9660; <u>Show example</u></button>
<div id="shdiv38748" style="display: none; margin-left: 15px;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    <span class="key">public</span> <span class="key">int</span> ProductId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span class="com">// Timestamp for concurrency control</span>
    <span style="background:#f2f19d;">[Timestamp]</span>
    <span class="key">public</span> byte[] RowVersion { get; set; }
} </code></pre>
</div>



<p class="custp1 p-mb-0"><strong>2. Handling Concurrency Conflicts:</strong></p>



<p class="pt5 p-mb-0 p-lp-15">To handle concurrency exceptions, you catch the <span class="spanHT">DbUpdateConcurrencyException</span> in your code and decide how to resolve the conflict.</p>



<button class="shbtn" id="shbtn8501" onclick="showHideBlock(8501)" style="margin-left: 15px;">&#9660; <u>Show example</u></button>
<div id="shdiv8501" style="display: none; margin-left: 15px;">
<pre class="pchl"><code><span class="key">try</span>
{
    context.SaveChanges();
}
<span class="key">catch</span> (<span style="background:#f2f19d;">DbUpdateConcurrencyException</span> ex)
{
    <span class="key">foreach</span> (<span class="key">var</span> entry <span class="key">in</span> ex.Entries)
    {
        <span class="key">if</span> (entry.Entity <span class="key">is</span> Product)
        {
            <span class="key">var</span> proposedValues = entry.CurrentValues;
            <span class="key">var</span> databaseValues = entry.GetDatabaseValues();

            <span class="com">// Decide how to handle the conflict</span>
            <span class="key">if</span> (databaseValues != <span class="key">null</span>)
            {
                <span class="com">// For example, resolve by choosing the database values</span>
                entry.OriginalValues.SetValues(databaseValues);
            }
        }
    }

    <span class="com">// Retry the save operation</span>
    context.SaveChanges();
} </code></pre>
</div>



<p class="custp1 p-mb-0"><strong>3. Marking Properties for Concurrency:</strong></p>



<p class="pt5 p-mb-0 p-lp-15">You can also mark specific properties for concurrency tracking using the <span class="spanHT">[ConcurrencyCheck]</span> attribute.</p>



<button class="shbtn" id="shbtn25032" onclick="showHideBlock(25032)" style="margin-left: 15px;">&#9660; <u>Show example</u></button>
<div id="shdiv25032" style="display: none; margin-left: 15px;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    <span class="key">public</span> <span class="key">int</span> ProductId { get; set; }

    <span style="background:#f2f19d;">[ConcurrencyCheck]</span>
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Migrations in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0"><strong>Migrations</strong> in Entity Framework are a way to manage and apply changes to your database schema over time, keeping it in sync with your model classes. When your model changes (like adding a new property, renaming a column, or creating a new table), migrations allow you to update the database schema without losing data.</p>



<p class="custp1 p-mb-0"><strong>Key Concepts of Migrations:</strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Tracking Changes</strong>: Migrations track changes made to your model (classes) and generate code to update the database accordingly.</li>



<li><strong>Version Control</strong>: Each migration is like a version of your database schema, allowing you to move forward or roll back to previous versions.</li>



<li><strong>Applying Changes</strong>: Migrations apply changes to the database using commands like <span class="spanHT">Add-Migration</span> and <span class="spanHT">Update-Database</span>.</li>
</ol>



<br>
<div>
<div style="background-color: #757e7e; color: #fff; padding: 5px 15px; border-radius: 10px 10px 0 0;">Add Migration Command:</div>
<div style="background-color: #000; color: #fff; padding: 15px;">dotnet ef migrations add MigrationName</div>
</div>
<br>
<div>
<div style="background-color: #757e7e; color: #fff; padding: 5px 15px; border-radius: 10px 10px 0 0;">Update Migration Command:</div>
<div style="background-color: #000; color: #fff; padding: 15px;">dotnet ef database update</div>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you roll back a migration in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">You can revert the database schema to a previous state using the <span class="spanHT">dotnet ef</span> commands. Rolling back a migration removes the changes applied by that migration and updates the schema to a prior version. </p>



<p class="custp1 p-mb-0"><strong>You can use the following commands:</strong></p>



<br>
<div>
<div style="background-color: #757e7e; color: #fff; padding: 5px 15px; border-radius: 10px 10px 0 0;">1. List All Migrations</div>
<div style="background-color: #000; color: #fff; padding: 15px;">dotnet ef migrations list</div>
</div>
<br>

<div>
<div style="background-color: #757e7e; color: #fff; padding: 5px 15px; border-radius: 10px 10px 0 0;">2. Rollback to a Specific Migration</div>
<div style="background-color: #000; color: #fff; padding: 15px;">dotnet ef database update PreviousOrSpecificMigrationName</div>
</div>
<br>

<div>
<div style="background-color: #757e7e; color: #fff; padding: 5px 15px; border-radius: 10px 10px 0 0;">3. Rollback All Migrations</div>
<div style="background-color: #000; color: #fff; padding: 15px;">dotnet ef database update 0</div>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How can you seed data in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0"><strong>Seeding data</strong> refers to the process of pre-populating the database with initial or default data. In EF Core, you can seed data during the migration process, ensuring that data is inserted when the database is first created or updated.</p>



<p class="custp1 p-mb-0"><strong>Steps to Seed Data in Entity Framework:</strong></p>



<p class="custp1 p-mb-0"><strong>1. Override the OnModelCreating Method:</strong> You seed data by overriding the <span class="spanHT">OnModelCreating</span> method of your <span class="spanHT">DbContext</span> and using the <span class="spanHT">HasData</span> method to specify the data to be inserted.</p>



<button class="shbtn" id="shbtn77103" onclick="showHideBlock(77103)">&#9660; <u>Show example</u></button>
<div id="shdiv77103" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span class="custkey">App<span class="custkey">DbContext</span></span> : <span class="custkey">DbContext</span>
{
    <span class="key">public</span> <span class="custkey">DbSet</span>&lt;<span class="custkey">Product</span>&gt Products { get; set; }

    <span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(<span class="custkey">ModelBuilder</span> modelBuilder)
    {
        <span class="com">// Seeding initial data</span>
        modelBuilder.Entity&lt;<span class="custkey">Product</span>&gt().<span style="background:#f2f19d;">HasData</span>(
            <span class="key">new</span> <span class="custkey">Product</span> { <span class="custkey">Product</span>Id = 1, Name = <span class="str">"Laptop"</span>, Price = 1200 },
            <span class="key">new</span> <span class="custkey">Product</span> { <span class="custkey">Product</span>Id = 2, Name = <span class="str">"Smartphone"</span>, Price = 800 }
        );
    }
}

<span class="key">public</span> <span class="key">class</span> <span class="custkey">Product</span>
{
    <span class="key">public</span> <span class="key">int</span> ProductId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> <span class="key">decimal</span> Price { get; set; }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">In this example, when the database is created or updated through a migration, it will be seeded with two products: Laptop and Smartphone.</div>

</div>



<p class="pt20 p-mb-0"><strong>2. Apply Migration with Seed Data:</strong> Once you&#8217;ve defined the seed data, you need to add a migration and update the database for the seeding to take effect.</p>



<br>
<div>
<div style="background-color: #757e7e; color: #fff; padding: 5px 15px; border-radius: 10px 10px 0 0;">a. Add Migration:</div>
<div style="background-color: #000; color: #fff; padding: 15px;">dotnet ef migrations add SeedInitialData</div>
</div>

<br>
<div>
<div style="background-color: #757e7e; color: #fff; padding: 5px 15px; border-radius: 10px 10px 0 0;">b. Update the database:</div>
<div style="background-color: #000; color: #fff; padding: 15px;">dotnet ef database update</div>
</div>



<p class="custp1 p-mb-0">This will insert the initial data into the <strong>Products</strong> table during migration.</p>



<p class="pt20 p-mb-0"><strong>Important Notes:</strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>HasData for Update</strong>: If the data already exists, <span class="spanHT">HasData</span> will not duplicate it. It only inserts new data.</li>



<li><strong>IDs are Required</strong>: For seeding to work, you must explicitly specify the primary key values (like <span class="spanHT">ProductId</span> in the example above).</li>



<li><strong>Migrations Only</strong>: Seeding through <span class="spanHT">HasData</span> works only during migration; if you use <span class="spanHT">DropCreateDatabaseIfModelChanges</span>, this seeding method doesn&#8217;t apply.</li>
</ul>



<br><br>



<p class="p-mb-0"><strong>Seeding Related Entities:</strong> You can also seed related entities by specifying foreign keys.</p>



<button class="shbtn" id="shbtn96092" onclick="showHideBlock(96092)">&#9660; <u>Show example</u></button>
<div id="shdiv96092" style="display: none;">
<pre class="pchl"><code>modelBuilder.Entity&lt;Category&gt().<span style="background:#f2f19d;">HasData</span>(
    <span class="key">new</span> Category { CategoryId = 1, Name = <span class="str">"Electronics"</span> }
);

modelBuilder.Entity&lt;<span class="custkey">Product</span>&gt().<span style="background:#f2f19d;">HasData</span>(
    <span class="key">new</span> <span class="custkey">Product</span> { <span class="custkey">Product</span>Id = 1, Name = <span class="str">"Laptop"</span>, Price = 1200, CategoryId = 1 }
); </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Explain how Entity Framework handles transactions.</strong></h3>



<p class="pt20 p-mb-0">There are 3 ways to handle transactions in EF:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Automatic Transactions (Default):</strong> <span class="spanHT">SaveChanges()</span> is automatically wrapped in a transaction. <br>When you call <span class="spanHT">SaveChanges()</span>, Entity Framework wraps all the changes in a transaction. If all the changes succeed, the transaction is committed. If any changes fail, the transaction is rolled back, ensuring that the database remains in a consistent state. <br> <button class="shbtnlist" id="shbtn13939" onclick="showHideBlock(13939)" fdprocessedid="6ey5lh">▼ <u>Show example</u></button> <div id="shdiv13939" style="display: none;"> 
<pre class="pchl"><code><span class="key">using</span> (<span class="key">var</span> context = <span class="key">new</span> <span class="custkey">AppDbContext</span>()) 
{     
	<span class="key">var</span> product = <span class="key">new</span> Product { 
		Name = <span class="str">"Laptop"</span>, 
		Price = 1200 
	};     
	context.Products.Add(product);     
	context.<span style="background:#f2f19d;"><b>SaveChanges()</b></span>;  <span class="com">// Automatically wrapped in a transaction</span> 
} </code></pre>
</div> </li>



<li class="pt20"><strong>Explicit Transactions:</strong> Use <span class="spanHT">BeginTransaction()</span> for manual control over transactions.<br>If you need more control over the transaction (e.g., for multiple SaveChanges() calls or to handle complex scenarios), you can manage the transaction explicitly using the DbContextTransaction object. <br> <button class="shbtnlist" id="shbtn54117" onclick="showHideBlock(54117)" fdprocessedid="uj5t5mm">▼ <u>Show example</u></button> <div id="shdiv54117" style="display: none;"> 
<pre class="pchl"><code><span class="key">using</span> (<span class="key">var</span> context = <span class="key">new</span> <span class="custkey">AppDbContext</span>()) 
{     
	<span style="background:#f2f19d;"><span class="key">using</span> (<span class="key">var</span> transaction = context.Database.<b>BeginTransaction()</b>)</span>     
	{         
		<span class="key">try</span>         
		{             
			<span class="com">// First operation</span>             
			<span class="key">var</span> product = <span class="key">new</span> Product { Name = <span class="str">"Smartphone"</span>, Price = 800 };             
			context.Products.Add(product);             
			context.SaveChanges();  <span class="com">// First save within the transaction</span>             
			
			<span class="com">// Second operation</span>             
			<span class="key">var</span> category = <span class="key">new</span> Category { Name = <span class="str">"Electronics"</span> };             
			context.Categories.Add(category);             
			context.SaveChanges();  <span class="com">// Second save within the same transaction</span>             
			
			<span class="com">// Commit transaction</span>             
			<span style="background:#f2f19d;">transaction.Commit();</span>         
		}         
		<span class="key">catch</span> (Exception)         
		{             
			<span class="com">// Rollback transaction if an error occurs</span>             
			<span style="background:#f2f19d;">transaction.Rollback();</span>         
		}     
	} 
} </code></pre> 
</div> </li>



<li class="pt20"><strong>Transaction Scope:</strong> Use <span class="spanHT">TransactionScope</span> for handling distributed transactions across multiple contexts or databases.<br> <button class="shbtnlist" id="shbtn68636" onclick="showHideBlock(68636)" fdprocessedid="vgvyk">▼ <u>Show example</u></button> <div id="shdiv68636" style="display: none;"> 
<pre class="pchl"><code><span style="background:#f2f19d;"><span class="key">using</span> (<span class="key">var</span> scope = <span class="key">new</span> <b>TransactionScope()</b>)</span> 
{     
	<span class="key">using</span> (<span class="key">var</span> context1 = <span class="key">new</span> <span class="custkey">AppDbContext</span>())     
	{         
		context1.Products.Add(<span class="key">new</span> Product { Name = <span class="str">"Tablet"</span>, Price = 500 });         
		context1.SaveChanges();     
	}     
	
	<span class="key">using</span> (<span class="key">var</span> context2 = <span class="key">new</span> AnotherDbContext())     
	{         
		context2.Orders.Add(<span class="key">new</span> Order { OrderId = 1, Quantity = 2 });         
		context2.SaveChanges();     
	}     
	
	<span class="com">// Commit the transaction across both contexts</span>     
	<span style="background:#f2f19d;">scope.Complete();</span> 
} </code></pre>
</div> </li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is ChangeTracker in EF?</strong></h3>



<p class="pt20 p-mb-0">The <strong>ChangeTracker</strong> is responsible for keeping track of the state of entities within the <span class="spanHT">DbContext</span>. It monitors changes made to the entities and determines what updates need to be sent to the database when <span class="spanHT">SaveChanges()</span> is called.</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1">It tracks the state of each entity (Added, Modified, Deleted, Unchanged, or Detached).</li>



<li class="custp1">This information is used to decide what operations (INSERT, UPDATE, DELETE) need to be performed in the database.</li>



<li class="custp1">You can enable or disable automatic change detection using the <span class="spanHT">AutoDetectChangesEnabled</span> property.<br>
<div style="background-color: #000; color: #fff; padding: 3px 15px; margin-top: 5px; border-radius: 5px;">context.ChangeTracker.AutoDetectChangesEnabled = false;</div>
</li>



<li class="custp1">You can access all tracked entities via <span class="spanHT">ChangeTracker.Entries()</span> to inspect their current state.</li>



<li class="custp1">You can use <span class="spanHT">ChangeTracker</span> for auditing purposes (e.g., to see what entities are being modified before saving changes) or for debugging entity state issues.</li>
</ul>



<button class="shbtn" id="shbtn7496" onclick="showHideBlock(7496)">&#9660; <u>Show example</u></button>
<div id="shdiv7496" style="display: none;">
<pre class="pchl"><code><span class="key">using</span> (<span class="key">var</span> context = <span class="key">new</span> <span class="custkey">AppDbContext</span>())
{
    <span class="key">var</span> product = context.Products.Find(1);
    product.Name = <span class="str">"New Laptop Name"</span>;

    <span class="com">// Inspecting the entity state</span>
    <span class="key">var</span> state = context.<b>Entry(product).State</b>;  <span class="com">// Returns EntityState.Modified</span>

    <span class="com">// Access all tracked entities</span>
    <span class="key">var</span> trackedEntities = context.<span style="background:#f2f19d;">ChangeTracker.Entries();</span>

    context.SaveChanges();  <span class="com">// ChangeTracker detects changes and updates the database</span>
} </code></pre>
</div>



<br><br><br><br><br>



<h2 class="wp-block-heading h2Cust1"><strong>Advanced Entity Framework Interview Questions</strong></h2>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between AsNoTracking and AsTracking?</strong></h3>



<p class="pt20 p-mb-0">In Entity Framework, <strong>AsTracking</strong> and <strong>AsNoTracking</strong> control how entities are tracked by the <strong>ChangeTracker</strong> in the <strong>DbContext</strong>. </p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>AsTracking (Default Behavior):</strong> <strong><em>Entities are tracked</em></strong> by the <span class="spanHT">DbContext</span> for changes. When you query data with <span class="spanHT">AsTracking</span>, EF Core tracks the returned entities and keeps track of any modifications made to them. This allows you to update or delete the entities easily by calling <span class="spanHT">SaveChanges()</span>. Use <span class="spanHT">AsTracking</span> when you modify or delete the returned entities. 
<br> 
<button class="shbtnlist" id="shbtn63554" onclick="showHideBlock(63554)" fdprocessedid="2yk2m8">▼ <u>Show example</u></button> 
<div id="shdiv63554" style="display: none;"> 
<pre class="pchl"><code><span class="key">var</span> product = context.Products.<span style="background:#f2f19d;">AsTracking()</span>.FirstOrDefault(p =&gt; p.ProductId == 1); 
product.Name = <span class="str">"Updated Name"</span>; 
context.<b>SaveChanges()</b>;  <span class="com">// The changes will be tracked and saved</span> </code></pre> 
</div> 
</li>



<li class="pt20"><strong>AsNoTracking:</strong> <strong><em>Entities are not tracked</em></strong> by the <span class="spanHT">DbContext</span>. EF Core does not monitor any changes made to the entities, meaning it performs better in read-only scenarios where changes are not needed.
<br>
<button class="shbtnlist" id="shbtn27364" onclick="showHideBlock(27364)">▼ <u>Show example</u></button>
<div id="shdiv27364" style="display: none;">
<pre class="pchl"><code><span class="key">var</span> product = context.Products.<span style="background:#f2f19d;">AsNoTracking()</span>.FirstOrDefault(p =&gt; p.ProductId == 1);
product.Name = <span class="str">"Updated Name"</span>;
context.SaveChanges();  <span class="com">// Changes will NOT be saved because the entity is not tracked</span></code></pre>
</div>
</li>
</ul>



<br><br>
<div><center><b>Difference Between &#39;AsNoTracking&#39; and &#39;AsTracking&#39;</b></center></div>
<table>
    <thead>
        <tr>
            <th>Feature</th>
            <th>AsTracking (Default)</th>
            <th>AsNoTracking</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Change Tracking</td>
            <td>Yes (Entities are tracked)</td>
            <td>No (Entities are not tracked)</td>
        </tr>
        <tr>
            <td>Use Case</td>
            <td>For CRUD operations (Update/Delete)</td>
            <td>For read-only operations</td>
        </tr>
        <tr>
            <td>Performance</td>
            <td>Slightly lower due to tracking overhead</td>
            <td>Higher performance (no tracking)</td>
        </tr>
        <tr>
            <td>Saving Changes</td>
            <td>Changes to entities are saved</td>
            <td>Changes to entities are not saved</td>
        </tr>
    </tbody>
</table>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you perform raw SQL queries in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">Raw SQL queries can be executed directly on the database using methods like <span class="spanHT">FromSql</span>(or <span class="spanHT">FromSqlRaw</span>) for querying entities and <span class="spanHT">ExecuteSql</span>(<span class="spanHT">ExecuteSqlRaw</span> or <span class="spanHT">ExecuteSqlCommand</span>) for non-query operations such as inserts, updates, and deletes.</p>



<button class="shbtn" id="shbtn44297" onclick="showHideBlock(44297)">&#9660; <u>Show example</u></button>
<div id="shdiv44297" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Raw SQL for Queries:</b> use the <span class="spanHT">FromSql</span> or <span class="spanHT">FromSqlRaw</span> method to perform SQL queries that return entity types.</div>
<pre class="pchl"><code><span class="key">var</span> products = context.Products
    .<span style="background:#f2f19d;">FromSqlRaw</span>(<span class="str">"SELECT * FROM Products WHERE Price > {0}"</span>, 1000)
    .ToList(); </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Raw SQL for Non-Entity Queries:</b> You can also execute raw SQL queries that return non-entity results or custom projections.</div>
<pre class="pchl"><code><span class="key">var</span> productNames = context.Products
    .<span style="background:#f2f19d;">FromSqlRaw</span>(<span class="str">"SELECT Name FROM Products"</span>)
    .Select(p =&gt p.Name)
    .ToList(); </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>3. Raw SQL for Non-Query Commands:</b> For non-query SQL commands like INSERT, UPDATE, or DELETE, you can use <span class="spanHT">ExecuteSqlRaw</span> or <span class="spanHT">ExecuteSqlCommand</span>.</div>
<pre class="pchl"><code><span class="key">int</span> rowsAffected = context.Database.<span style="background:#f2f19d;">ExecuteSqlRaw</span>(
    <span class="str">"UPDATE Products SET Price = Price * 1.1 WHERE CategoryId = {0}"</span>, 1); </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a Complex Type in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">A <strong>Complex Type</strong> in Entity Framework is a class that does not have a primary key and cannot exist independently in the database. It is used to represent a group of related fields (properties) within an entity, but it doesn&#8217;t get its own table. Instead, the properties of the complex type are stored in the same table as the owning entity. </p>



<p class="custp1 p-mb-0"><strong>Characteristics of a Complex Type: </strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>No Primary Key</strong>: Unlike entities, complex types do not have a primary key and cannot be queried or tracked individually.</li>



<li><strong>Embedded in an Entity</strong>: Complex types are always part of another entity and cannot exist on their own.</li>



<li><strong>Reusability</strong>: You can reuse a complex type across multiple entities, encapsulating common properties.</li>



<li><strong>Stored in the Same Table</strong>: The properties of a complex type are mapped to columns in the same table as the entity it belongs to.</li>
</ul>



<button class="shbtn" id="shbtn99570" onclick="showHideBlock(99570)">&#9660; <u>Show example</u></button>
<div id="shdiv99570" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1)</b> Let&#8217;s say you have an <span class="spanHT">Address</span> class that groups address-related fields. This class can be used as a complex type in multiple entities, such as <span class="spanHT">Customer</span> and <span class="spanHT">Supplier</span>.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span style="background:#f2f19d;">Address</span>
{
    <span class="key">public</span> <span class="key">string</span> Street { get; set; }
    <span class="key">public</span> <span class="key">string</span> City { get; set; }
    <span class="key">public</span> <span class="key">string</span> State { get; set; }
    <span class="key">public</span> <span class="key">string</span> ZipCode { get; set; }
}

<span class="key">public</span> <span class="key">class</span> Customer
{
    <span class="key">public</span> <span class="key">int</span> CustomerId { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> <span style="background:#f2f19d;">Address Address</span> { get; set; }  <span class="com">// Complex type used here</span>
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2) Mapping of Complex Types:</b> In EF Core, complex types are called Owned Types. To define <span class="spanHT">Address</span> as a complex type, you can configure it using the <span class="spanHT">OwnsOne</span> method in the <span class="spanHT">OnModelCreating</span> method of your <span class="spanHT">DbContext</span>.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> AppDbContext : <b>DbContext</b>
{
    <span class="key">public</span> DbSet&lt;Customer&gt Customers { get; set; }

    <span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> <b>OnModelCreating</b>(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&lt;Customer&gt()
            .<span style="background:#f2f19d;">OwnsOne</span>(c =&gt c.Address);  <span class="com">// Configuring Address as an owned type</span>
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>3) Table Structure:</b> In the database, the <span class="spanHT">Address</span> fields (Street, City, State, ZipCode) will be stored as columns in the same table as the <span class="spanHT">Customer</span>, rather than in a separate table.</div>
<br>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How does Entity Framework support TPT, TPH, and TPC inheritance strategies?</strong></h3>



<p class="pt20 p-mb-0">Entity Framework (EF) supports three types of inheritance mapping strategies to model inheritance in relational databases: <strong>TPT (Table Per Type)</strong>, <strong>TPH (Table Per Hierarchy)</strong>, and <strong>TPC (Table Per Concrete Class)</strong>. These strategies allow you to represent object-oriented inheritance in your data models while persisting them in relational databases. </p>



<p class="pt20 p-mb-0"><strong>1. TPH (Table Per Hierarchy)</strong>: </p>



<p class="p-lp-15 pt5 p-mb-0">In <strong>Table Per Hierarchy</strong>, all classes in an inheritance hierarchy are stored in a single database table. A <strong>discriminator column</strong> is used to distinguish between the different entity types. </p>



<p class="p-lp-15 custp1 p-mb-0"><strong>Pros:</strong> Simple to implement. Better performance (single table query).<br><strong>Cons:</strong> The table can become sparse (many <strong>NULL</strong> values) if the base and derived classes have many different properties.</p>



<div class="p-lp-15">
<button class="shbtn" id="shbtn32956" onclick="showHideBlock(32956)">&#9660; <u>Show example</u></button>
<div id="shdiv32956" style="display: none;" class="shdt">
<br>
<pre class="pchl" style="margin-left: 0.3125rem;"><code><span class="key">public</span> <span class="key">class</span> Animal
{
    <span class="key">public</span> <span class="key">int</span> Id { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
}

<span class="key">public</span> <span class="key">class</span> Dog : Animal
{
    <span class="key">public</span> <span class="key">string</span> Breed { get; set; }
}

<span class="key">public</span> <span class="key">class</span> Cat : Animal
{
    <span class="key">public</span> <span class="key">bool</span> IsIndoor { get; set; }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>Database Schema</b> (Single Table with Discriminator):</div>
<div style="padding-left: 0.3125rem;">
<table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Breed</th>
            <th>IsIndoor</th>
            <th>Discriminator</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Max</td>
            <td>Labrador</td>
            <td>NULL</td>
            <td>Dog</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Whiskers</td>
            <td>NULL</td>
            <td>True</td>
            <td>Cat</td>
        </tr>
    </tbody>
</table>
</div>

<br><br>
<div style="padding-left: 0.3125rem;"><b>Configuration</b> (EF Core automatically uses TPH by default):</div>
<pre class="pchl" style="margin-left: 0.3125rem;"><code>modelBuilder.Entity&lt;Animal&gt()
            .<span style="background:#f2f19d;">HasDiscriminator&lt;<span class="key">string</span>&gt(<span class="str">"Discriminator"</span>)</span>
            .HasValue&lt;Dog&gt(<span class="str">"Dog"</span>)
            .HasValue&lt;Cat&gt(<span class="str">"Cat"</span>); </code></pre>
</div>

</div>
<br>



<p class="pt20 p-mb-0"><strong>2. TPT (Table Per Type)</strong>:</p>



<p class="p-lp-15 pt5 p-mb-0">In <strong>Table Per Type</strong>, each class in the inheritance hierarchy has its own table in the database. The base class&#8217;s properties are stored in a base table, and each derived class has a separate table storing only the properties unique to that class.</p>



<p class="p-lp-15 custp1 p-mb-0"><strong>Pros:</strong> No NULL values, as each class has its own table. Normalized table structure.<br><strong>Cons:</strong> Requires JOINs when querying derived types, which can affect performance.</p>



<p class="pt20 p-mb-0"><strong>3. TPC (Table Per Concrete Class):</strong></p>



<p class="p-lp-15 pt5 p-mb-0">In Table Per Concrete Class, each concrete class (the base class and all derived classes) is mapped to its own table, containing all the properties of that class (including inherited properties). There is no table for the base class.</p>



<p class="p-lp-15 custp1 p-mb-0"><strong>Pros:</strong> No joins are required since each class has its own table. Better performance when querying only derived types.<br><strong>Cons:</strong> Data duplication: Properties inherited from the base class are duplicated in each derived class&#8217;s table. More storage space is required due to duplication.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle database connection strings in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">Here are common ways to manage connection strings in EF Core:</p>



<ol class="wp-block-list">
<li>Storing Connection Strings in <strong>appsettings.json</strong> <br> <button class="shbtnlist" id="shbtn29137" onclick="showHideBlock(29137)" fdprocessedid="4kokro">▼ <u>Show example</u></button> <div id="shdiv29137" style="display: none;" class="shdt"> <br> <div style="padding-left: 0.3125rem;">This is a standard approach, where connection strings are stored in the appsettings.json file for easy configuration.</div> <div style="padding-left: 0.3125rem;" class="custp1"><b><u>example:</u></b></div> 
<pre class="pchl"><code>{   
	<span class="str">"ConnectionStrings"</span>: 
		{     
			<span class="str">"DefaultConnection"</span>: <span class="str">"Server=myServer;Database=myDB;User Id=myUser;Password=myPassword;"</span>   
		} 
	} </code></pre> 
<br> <div style="padding-left: 0.3125rem;"><b>Using in DbContext:</b> You can retrieve the connection string in DbContext using dependency injection.</div> 
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> AppDbContext : DbContext
{
    <span class="key">public</span> AppDbContext(DbContextOptions&lt;AppDbContext&gt; options) : <span class="key">base</span>(options) { }

    <span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        <span class="key">if</span> (!optionsBuilder.IsConfigured)
        {
            <span class="key">var</span> connectionString = <span class="str">"YourConnectionStringHere"</span>;
            optionsBuilder.UseSqlServer(connectionString);
        }
    }
} </code></pre>
</div> <br> </li>



<li class="custp1">Accessing Connection Strings via <strong>Dependency Injection</strong><br> <button class="shbtnlist" id="shbtn1583" onclick="showHideBlock(1583)" fdprocessedid="htvtuh">▼ <u>Show example</u></button> <div id="shdiv1583" style="display: none;" class="shdt"> <br> <div style="padding-left: 0.3125rem;">Retrieve the connection string in <b>Startup.cs</b> and pass it to the <b>DbContext</b>.</div> <div style="padding-left: 0.3125rem;" class="custp1"><b><u>example:</u></b></div> <pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="custkey">IConfiguration</span> Configuration { get; }

    <span class="key">public</span> Startup(<span class="custkey">IConfiguration</span> configuration)
    {
        Configuration = configuration;
    }

    <span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext&lt;AppDbContext&gt;(options =&gt;
            options.UseSqlServer(Configuration.GetConnectionString(<span class="str">"DefaultConnection"</span>)));
    }
} </code></pre> </div> <br> </li>



<li class="custp1">Connection Strings for <strong>Multiple Environments</strong>: Use multiple <span class="spanHT">appsettings.{Environment}.json</span> files (<strong>e.g.</strong>, <em>appsettings.Development.json</em> and <em>appsettings.Production.json</em>) for different configurations based on the environment.</li>



<li class="custp1"><strong>Environment-Specific</strong> Configuration:
<br>
<button class="shbtnlist" id="shbtn30243" onclick="showHideBlock(30243)">▼ <u>Show example</u></button>
<div id="shdiv30243" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;">
<div>Using environment variables or secrets is useful in scenarios where sensitive information like passwords shouldn&#8217;t be stored in code.</div>
<br>
<div style="background-color: #757e7e; color: #fff; padding: 5px 15px; border-radius: 10px 10px 0 0;">a. <b>Environment Variables:</b> Set the connection string as an environment variable, especially for production environments.</div>
<div style="background-color: #000; color: #fff; padding: 15px;">export ConnectionStrings__DefaultConnection=&#8221;YourConnectionStringHere&#8221;</div>

<br>
<div style="background-color: #757e7e; color: #fff; padding: 5px 15px; border-radius: 10px 10px 0 0;">b. <b>User Secrets:</b> For local development, use User Secrets to securely store the connection string outside of source control.</div>
<div style="background-color: #000; color: #fff; padding: 15px;">dotnet user-secrets set &#8220;ConnectionStrings:DefaultConnection&#8221; &#8220;YourConnectionStringHere&#8221;
</div>


</div>
<br>
<div style="padding-left: 0.3125rem;" class="custp1">Then, access it in <b>appsettings.json:</b></div>
<pre class="pchl"><code>{
  <span class="str">"ConnectionStrings"</span>: {
    <span class="str">"DefaultConnection"</span>: <span class="str">"YourConnectionStringHere"</span>
  }
} </code></pre>

</div>
<br>
</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement Soft Deletes?</strong></h3>



<p class="pt20 p-mb-0"><strong>Soft deletes</strong> allow you to mark an entity as deleted without actually removing it from the database. This approach helps preserve data history and supports data recovery. </p>



<p class="custp1 p-mb-0">Instead of deleting the entity, set the property value <span class="spanHT">IsDeleted</span> to <span class="spanHT">true</span> in your application code.</p>



<button class="shbtn" id="shbtn6467" onclick="showHideBlock(6467)">&#9660; <u>Show example</u></button>
<div id="shdiv6467" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> SoftDeleteProduct(<span class="key">int</span> productId)
{
    <span class="key">var</span> product = context.Products.Find(productId);
    <span class="key">if</span> (product != <span class="key">null</span>)
    {
        <span style="background:#f2f19d;">product.IsDeleted = true;</span>
        context.SaveChanges();
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Explain what the SaveChanges method does internally.</strong></h3>



<p class="pt20 p-mb-0">Detects changes, generates commands, executes them in a transaction, and updates <span class="spanHT">Change Tracker</span>.</p>



<p class="custp1"><strong>Example</strong> &#8211; If you add, modify, or delete several <span class="spanHT">Order</span> and <span class="spanHT">Customer</span> entities and then call <span class="spanHT">SaveChanges</span>, EF Core will:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li>Detect which entities are new, modified, or deleted.</li>



<li>Generate the necessary <span class="spanHT">INSERT</span>, <span class="spanHT">UPDATE</span>, and <span class="spanHT">DELETE</span> commands.</li>



<li>Begin a transaction.</li>



<li>Execute the commands in the correct order.</li>



<li>Commit the transaction if all commands succeed or roll back if any command fails.</li>



<li>Update the <span class="spanHT">Change Tracker</span> to mark these changes as saved.</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How can you log SQL queries generated by Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">Entity Framework Core provides built-in support for logging SQL queries, making it easier to monitor or debug the SQL statements generated by your LINQ queries. Here’s how you can log SQL queries in different ways:</p>



<p class="custp1 p-mb-0"><strong>1. Using ILogger with Dependency Injection:</strong> </p>



<div class="p-lp-15"> 
<button class="shbtnlist" id="shbtn34549" onclick="showHideBlock(34549)">&#9660; <u>Show example</u></button>
<div id="shdiv34549" style="display: none;" class="shdt">
<br>
<div style="padding-left: 0.3125rem;"><b>1. Configure Logging in DbContext:</b> Add an &#39;ILoggerFactory&#39; to your &#39;DbContext&#39; to capture SQL queries.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span class="custkey">AppDbContext</span> : DbContext
{
    <span class="key">private</span> <span class="key">readonly</span> <span class="custkey">ILoggerFactory</span> _loggerFactory;

    <span class="key">public</span> <span class="custkey">AppDbContext</span>(DbContextOptions&lt;<span class="custkey">AppDbContext</span>&gt options, <span class="custkey">ILoggerFactory</span> loggerFactory)
        : <span class="key">base</span>(options)
    {
        _loggerFactory = loggerFactory;
    }

    <span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> <span class="custkey">OnConfiguring</span>(DbContextOptionsBuilder optionsBuilder)
    {
        <span class="key">if</span> (_loggerFactory != <span class="key">null</span>)
        {
            <span style="background:#f2f19d;">optionsBuilder.UseLoggerFactory(_loggerFactory)</span>; <span class="com">// Enable logging</span>
        }
    }
} </code></pre>
<br>
<br>
<div style="padding-left: 0.3125rem;"><b>2. Configure Logging in Startup.cs:</b> Define a logging provider (e.g., Console) in &#39;ConfigureServices&#39;.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
{
    services.AddLogging(config =&gt {
        config.AddConsole();
        config<span style="background:#f2f19d;">.SetMinimumLevel(LogLevel.Information)</span>; <span class="com">// Choose log level</span>
    });

    services.AddDbContext&lt;<span class="custkey">AppDbContext</span>&gt(options =&gt
        options.UseSqlServer(Configuration.GetConnectionString(<span class="str">"DefaultConnection"</span>)));
} </code></pre>
<br>
<br>
<div style="padding-left: 0.3125rem;"><b>3. Adjust Log Level:</b> Set the minimum log level to Information or Debug to capture SQL queries.</div>
<br>

</div>
<br>
</div>



<p class="custp1 p-mb-0"><strong>2. Using EnableSensitiveDataLogging:</strong> When logging queries, you may need to see parameter values. EF Core’s <span class="spanHT">EnableSensitiveDataLogging</span> method includes these values but should only be used in development, as it may expose sensitive data.</p>



<div class="p-lp-15"> 
<button class="shbtnlist" id="shbtn61748" onclick="showHideBlock(61748)">&#9660; <u>Show example</u></button>
<div id="shdiv61748" style="display: none;">
<pre class="pchl"><code>optionsBuilder
    .UseSqlServer(<span class="str">"YourConnectionString"</span>)
    <span style="background:#f2f19d;">.EnableSensitiveDataLogging();</span> </code></pre>
</div>
<br>
</div>



<p class="custp1 p-mb-0"><strong>3. Using Application Insights (or Other External Loggers):</strong> If your application integrates with logging services like <span class="spanHT">Application Insights</span> or <span class="spanHT">Serilog</span>, you can capture EF Core logs there.</p>



<div class="p-lp-15"> 
<button class="shbtnlist" id="shbtn63183" onclick="showHideBlock(63183)">&#9660; <u>Show example</u></button>
<div id="shdiv63183" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
{
    services.AddLogging(config =&gt; {
        config<span style="background:#f2f19d;">.AddApplicationInsights(<span class="str">"YourInstrumentationKey"</span>)</span>;
    });
} </code></pre>
</div>
</div>



<p class="custp1 p-mb-0"><strong>4. Console Logging (For Quick Setup):</strong> For simple applications, you can enable console logging directly when configuring the DbContext.</p>



<div class="p-lp-15"> 
<button class="shbtnlist" id="shbtn59457" onclick="showHideBlock(59457)">&#9660; <u>Show example</u></button>
<div id="shdiv59457" style="display: none;">
<pre class="pchl"><code>optionsBuilder
    .UseSqlServer(<span class="str">"YourConnectionString"</span>)
    .<span style="background:#f2f19d;">LogTo(Console.WriteLine, LogLevel.Information)</span>; </code></pre>
</div>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Shadow Property in Entity Framework Core?</strong></h3>



<p class="pt20 p-mb-0">A <strong>Shadow Property</strong> in Entity Framework Core is a property that exists only in the database, not in the .NET entity class, for example &#8211; &#8220;<strong>CreatedDate</strong>&#8221; column in the Database. EF creates and manages these properties and can be useful for storing data you don’t need directly in your entity model.</p>



<p class="custp1 p-mb-0">You can set or access shadow properties using <span class="spanHT">Entry</span> and <span class="spanHT">Property</span> methods.</p>



<button class="shbtn" id="shbtn76297" onclick="showHideBlock(76297)">&#9660; <u>Show example</u></button>
<div id="shdiv76297" style="display: none;" class="shdt">
<br>
<div style="padding-left: 0.3125rem;"><b>1.</b> Define Shadow Property using Fluent API:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span class="custkey">AppDbContext</span> : DbContext
{
    <span class="key">public</span> DbSet&lt;Product&gt Products { get; set; }

    <span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&lt;Product&gt()
            .<span style="background:#f2f19d;">Property&lt;DateTime&gt(<span class="str">"CreatedDate"</span>)</span>;  <span class="com">// Define shadow property</span>
    }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2.</b> Shadow properties can be set or accessed using &#39;Entry&#39; and &#39;Property&#39; methods.
</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> AddProduct(Product product)
{
    context.Products.Add(product);
    context.<span style="background:#f2f19d;">Entry(product).Property(<span class="str">"CreatedDate"</span>).CurrentValue</span> = DateTime.Now;  <span class="com">// Set shadow property</span>
    context.SaveChanges();
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Global Query Filter in Entity Framework Core?</strong></h3>



<p class="pt20 p-mb-0">A <strong>Global Query Filter</strong> is a filter applied to all queries for a specific entity type. It’s defined in <span class="spanHT">OnModelCreating</span> using the Fluent API and is commonly used for scenarios like <strong>soft deletes</strong> or <strong>multi-tenancy</strong>, where you want to filter out records based on a condition (e.g., <span class="spanHT">IsDeleted = false</span>).</p>



<button class="shbtn" id="shbtn20096" onclick="showHideBlock(20096)">&#9660; <u>Show example</u></button>
<div id="shdiv20096" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity&lt;Product&gt().<span style="background:#f2f19d;">HasQueryFilter(p =&gt !p.IsDeleted)</span>;
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use a Composite Key in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">A Composite Key is defined when an entity requires multiple columns to identify a record uniquely. You can configure it using the Fluent API in the &#8216;OnModelCreating&#8217; method. </p>



<button class="shbtn" id="shbtn87325" onclick="showHideBlock(87325)">&#9660; <u>Show example</u></button>
<div id="shdiv87325" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> OrderDetail
{
    <span class="key">public</span> <span class="key">int</span> OrderId { get; set; }
    <span class="key">public</span> <span class="key">int</span> ProductId { get; set; }
    <span class="key">public</span> <span class="key">int</span> Quantity { get; set; }
}

<span class="key">public</span> <span class="key">class</span> <span class="custkey">AppDbContext</span> : DbContext
{
    <span class="key">public</span> DbSet&lt;OrderDetail&gt OrderDetails { get; set; }

    <span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&lt;OrderDetail&gt()
            .<span style="background:#f2f19d;">HasKey(od =&gt <span class="key">new</span> { od.OrderId, od.ProductId })</span>;  <span class="com">// Define composite key</span>
    }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">In this example, &#39;OrderId&#39; and &#39;ProductId&#39; together form a composite key for &#39;OrderDetail&#39;. This ensures uniqueness across both columns.</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the ModelBuilder class in EF?</strong></h3>



<p class="pt20 p-mb-0">The <strong>ModelBuilder</strong> class in Entity Framework is used to configure entity properties, relationships, and database mappings through the Fluent API. It’s typically used in the <strong>OnModelCreating</strong> method of <strong>DbContext</strong> to define table structures, keys, constraints, and other model configurations that are not set by default.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the differences between &#8216;FirstOrDefault&#8217; and &#8216;SingleOrDefault&#8217;?</strong></h3>



<p class="has-text-align-center pt20 p-mb-0"><strong>FirstOrDefault Vs SingleOrDefault</strong></p>



<table style="margin-top: 0.3125rem;">
    <thead>
        <tr>
            <th>FirstOrDefault</th>
            <th>SingleOrDefault</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Returns the first matching element or null if none is found.</td>
            <td>Returns the only matching element or null if none is found.</td>
        </tr>
        <tr>
            <td>Used when you need the first match and don’t require uniqueness.</td>
            <td>Used when you expect only one match and need uniqueness.</td>
        </tr>
        <tr>
            <td>Generally faster, stops after finding the first match.</td>
            <td>Slower, as it checks the entire set for uniqueness.</td>
        </tr>
        <tr>
            <td>No exception if multiple matches exist.</td>
            <td>Throws an exception if multiple matches are found.</td>
        </tr>
    </tbody>
</table>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you detach an entity from the DbContext?</strong></h3>



<p class="pt20 p-mb-0">To detach an entity from the <span class="spanHT">DbContext</span>, use the <span class="spanHT">Entry</span> method combined with <span class="spanHT">State</span> property to set the state of the entity to <span class="spanHT">Detached</span>. Detaching an entity does not affect the database; it simply removes the entity from the context&#8217;s tracking. </p>



<p class="custp1 p-mb-0">You can also detach all entities if needed using <span class="spanHT">context.ChangeTracker.Clear()</span>, which detaches all entities being tracked by the context.</p>



<button class="shbtn" id="shbtn57626" onclick="showHideBlock(57626)">&#9660; <u>Show example</u></button>
<div id="shdiv57626" style="display: none;">
<pre class="pchl"><code><span class="key">var</span> product = context.Products.Find(productId);  <span class="com">// Retrieve the entity</span>
context.Entry(product).State = <span style="background:#f2f19d;">EntityState.Detached</span>;  <span class="com">// Detach the entity</span>
</code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the ‘Find’ method in Entity Framework, and how does it work?</strong></h3>



<p class="pt20 p-mb-0">The <strong>Find method</strong> in Entity Framework retrieves an entity by its primary key. It first checks the <span class="spanHT">Change Tracker</span> for a tracked entity; if found, it returns it without querying the database. If not, it performs a database query to fetch the entity. It returns the entity if found, or <span class="spanHT">null</span> if not.</p>



<pre class="pchl"><code><span class="key">var</span> product = context.Products.<span style="background:#f2f19d;">Find(productId)</span>;
</code></pre>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use Stored Procedures with Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">In EF, you can use <strong>stored procedures</strong> by executing raw SQL commands like <span class="spanHT">FromSqlRaw</span> to get records or <span class="spanHT">ExecuteSqlRaw</span> to insert data. EF Core allows mapping stored procedures to entity queries or using them for data modifications.</p>



<button class="shbtn" id="shbtn57588" onclick="showHideBlock(57588)">&#9660; <u>Show example</u></button>
<div id="shdiv57588" style="display: none;" class="shdt">
<br>
<div style="padding-left: 0.3125rem;"><b>1. </b>Stored procedure that retrieves data, use <b>FromSqlRaw</b>:</div>
<pre class="pchl"><code><span class="key">var</span> categoryParam = <span class="key">new</span> SqlParameter(<span class="str">"Category"</span>, <span class="str">"Electronics"</span>);
<span class="key">var</span> products = context.Products
    .<span style="background:#f2f19d;">FromSqlRaw</span>(<span class="str">"EXEC GetProductsByCategory @Category"</span>, categoryParam)
    .ToList(); </code></pre>
<br><br>
<div style="padding-left: 0.3125rem;"><b>2. </b>To run a stored procedure that inserts data, use <b>ExecuteSqlRaw</b>:</div>
<pre class="pchl"><code>context.Database.<span style="background:#f2f19d;">ExecuteSqlRaw</span>(<span class="str">"EXEC InsertProduct @Name, @Price"</span>, 
    <span class="key">new</span> SqlParameter(<span class="str">"Name"</span>, <span class="str">"Laptop"</span>), 
    <span class="key">new</span> SqlParameter(<span class="str">"Price"</span>, 1200)); </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between Remove and RemoveRange?</strong></h3>



<p class="has-text-align-left pt20 p-mb-0"><strong>Remove:</strong> Deletes a single entity from the database. Use when you want to delete one specific entity.</p>



<p class="custp1 p-mb-0"><strong>RemoveRange:</strong> Deletes multiple entities at once. Accepts a collection of entities. Use when you want to delete multiple entities in a single operation for better performance.</p>



<pre class="pchl"><code><span class="com">// Remove a single entity</span>
context.Products.Remove(product);

<span class="com">// Remove multiple entities</span>
context.Products.RemoveRange(products); </code></pre>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle exceptions in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">Use <span class="spanHT">try-catch</span> blocks to catch specific EF-related exceptions and handle them accordingly. Some common exception types include <span class="spanHT">DbUpdateException</span>, <span class="spanHT">DbUpdateConcurrencyException</span>, and <span class="spanHT">SqlException</span> (for SQL Server).</p>



<button class="shbtn" id="shbtn65331" onclick="showHideBlock(65331)">&#9660; <u>Show example</u></button>
<div id="shdiv65331" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">try</span>
{
    context.SaveChanges();
}
<span class="key">catch</span> (DbUpdateException ex)
{
    <span class="com">// Handle database update issues (e.g., foreign key violations)</span>
    Console.WriteLine(<span class="str">"Database update error: "</span> + ex.Message);
}
<span class="key">catch</span> (DbUpdateConcurrencyException ex)
{
    <span class="com">// Handle concurrency conflicts</span>
    Console.WriteLine(<span class="str">"Concurrency error: "</span> + ex.Message);
}
<span class="key">catch</span> (Exception ex)
{
    <span class="com">// Handle other exceptions</span>
    Console.WriteLine(<span class="str">"An error occurred: "</span> + ex.Message);
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between DbQuery and DbSet?</strong></h3>



<p class="has-text-align-center pt20 p-mb-0">Differences between DbQuery and DbSet</p>



<table style="margin-top:10px">
    <thead>
        <tr>
            <th>DbSet</th>
            <th>DbQuery (EF Core 2.1 and earlier)</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Represents a table in the database for CRUD operations.</td>
            <td>Represents a database view or query that is read-only.</td>
        </tr>
        <tr>
            <td>Supports both read and write operations (e.g., Add, Update, Remove).</td>
            <td>Supports read-only operations; cannot be used for insert, update, or delete.</td>
        </tr>
        <tr>
            <td>Tracks changes to entities, enabling updates to the database on SaveChanges().</td>
            <td>Does not track changes, so it’s ideal for read-only data that doesn’t need tracking.</td>
        </tr>
        <tr>
            <td>Use for entities that need full CRUD capabilities.</td>
            <td>Use for read-only data, such as views or non-updatable queries.</td>
        </tr>
    </tbody>
</table>



<br><br><br><br><br>



<h2 class="wp-block-heading h2Cust1"><strong>Entity Framework with ASP.NET Core</strong></h2>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you integrate Entity Framework Core with ASP.NET Core?</strong></h3>



<ol class="pt20 p-mb-0 wp-block-list">
<li>Install EF Core Packages</li>



<li>Define DbContext</li>



<li>Configure DbContext in Startup or Program</li>



<li>Add Connection String</li>



<li>Inject and Use DbContext in Controllers</li>
</ol>



<button class="shbtn" id="shbtn26849" onclick="showHideBlock(26849)">&#9660; <u>Show example</u></button>
<div id="shdiv26849" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Install EF Core Packages:</b></div>
<div style="background-color: #000; color: #fff; padding: 15px; margin-top:10px;">dotnet add package Microsoft.EntityFrameworkCore.SqlServer
</div>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Define Your DbContext:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> AppDbContext : DbContext
{
    <span class="key">public</span> AppDbContext(DbContextOptions&lt;AppDbContext&gt options) : <span class="key">base</span>(options) { }

    <span class="key">public</span> DbSet&lt;Product&gt Products { get; set; }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>3. Configure DbContext in Startup.cs:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext&lt;AppDbContext&gt(options =&gt
            options.<span style="background:#f2f19d;">UseSqlServer</span>(Configuration.GetConnectionString(<span class="str">"DefaultConnection"</span>)));
        
        services.AddControllers();  <span class="com">// Register MVC or API controllers</span>
    }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>4. Configure Connection String:</b> Add the connection string to &#39;appsettings.json&#39;.</div>
<pre class="pchl"><code>{
  <span class="str">"ConnectionStrings"</span>: {
    <span class="str">"DefaultConnection"</span>: <span class="str">"Server=your_server;Database=your_db;User Id=your_user;Password=your_password;"</span>
  }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>5. Use DbContext in Controllers:</b> Inject &#39;AppDbContext&#39; into your controllers or services to access the database.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    <span class="key">private</span> <span class="key">readonly</span> AppDbContext _context;

    <span class="key">public</span> ProductsController(<span style="background:#f2f19d;">AppDbContext context</span>)
    {
        _context = context;
    }

    [HttpGet]
    <span class="key">public</span> <span class="key">async</span> Task&lt;ActionResult&lt;IEnumerable&lt;Product&gt&gt&gt GetProducts()
    {
        <span class="key">return</span> <span class="key">await</span> <span style="background:#f2f19d;">_context</span>.Products.ToListAsync();
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Dependency Injection, and how is it used with Entity Framework in ASP.NET Core?</strong></h3>



<p class="pt20 p-mb-0"><strong>Dependency Injection (DI)</strong> is a design pattern in which dependencies (e.g., services, configurations) are provided to a class rather than the class creating them itself. This promotes loose coupling and makes code easier to maintain and test. In ASP.NET Core, DI is built-in and widely used.</p>



<p class="custp1 p-mb-0"><strong>How It’s Used with Entity Framework in ASP.NET Core &#8211; Example:</strong> you can register your <span class="spanHT">DbContext</span> as a service and inject it where needed (e.g., in controllers or services).</p>



<button class="shbtn" id="shbtn88584" onclick="showHideBlock(88584)">&#9660; <u>Show example</u></button>
<div id="shdiv88584" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    <span class="key">private</span> <span class="key">readonly</span> AppDbContext _context;

    <span class="key">public</span> ProductsController(<span style="background:#f2f19d;">AppDbContext context</span>)
    {
        _context = context;
    }

    [HttpGet]
    <span class="key">public</span> <span class="key">async</span> Task&lt;ActionResult&lt;IEnumerable&lt;Product&gt&gt&gt GetProducts()
    {
        <span class="key">return</span> <span class="key">await</span> <span style="background:#f2f19d;">_context</span>.Products.ToListAsync();
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you configure multiple DbContexts in an ASP.NET Core application?</strong></h3>



<p class="pt20 p-mb-0">To configure multiple <strong>DbContext</strong> classes in an ASP.NET Core application, register each <strong>DbContext</strong> with a unique configuration in &#8216;Startup.cs&#8217;. This allows you to connect to multiple databases or use different contexts for different parts of the application.</p>



<button class="shbtn" id="shbtn36670" onclick="showHideBlock(36670)">&#9660; <u>Show example</u></button>
<div id="shdiv36670" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Define Multiple DbContext Classes:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> AppDbContext : DbContext
{
    <span class="key">public</span> <span style="background:#f2f19d;">AppDbContext</span>(DbContextOptions&lt;AppDbContext&gt options) : <span class="key">base</span>(options) { }
    <span class="key">public</span> DbSet&lt;Product&gt Products { get; set; }
}

<span class="key">public</span> <span class="key">class</span> LoggingDbContext : DbContext
{
    <span class="key">public</span> <span style="background:#f2f19d;">LoggingDbContext</span>(DbContextOptions&lt;LoggingDbContext&gt options) : <span class="key">base</span>(options) { }
    <span class="key">public</span> DbSet&lt;LogEntry&gt LogEntries { get; set; }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Register Each DbContext in Startup.cs</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
{
    services.AddDbContext&lt;<span style="background:#f2f19d;">AppDbContext</span>&gt(options =&gt
        options.UseSqlServer(Configuration.GetConnectionString(<span class="str">"AppConnection"</span>)));
    
    services.AddDbContext&lt;<span style="background:#f2f19d;">LoggingDbContext</span>&gt(options =&gt
        options.UseSqlServer(Configuration.GetConnectionString(<span class="str">"LoggingConnection"</span>)));
    
    services.AddControllers();
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>3. Inject Specific DbContext as Needed:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    <span class="key">private</span> <span class="key">readonly</span> AppDbContext _appContext;

    <span class="key">public</span> ProductsController(<span style="background:#f2f19d;">AppDbContext appContext</span>)
    {
        _appContext = appContext;
    }
}

<span class="key">public</span> <span class="key">class</span> LogsController : ControllerBase
{
    <span class="key">private</span> <span class="key">readonly</span> LoggingDbContext _logContext;

    <span class="key">public</span> LogsController(<span style="background:#f2f19d;">LoggingDbContext logContext</span>)
    {
        _logContext = logContext;
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How can you implement Unit of Work and Repository patterns with Entity Framework in ASP.NET Core?</strong></h3>



<p class="pt20 p-mb-0">To implement the <strong>Unit of Work</strong> and <strong>Repository</strong> patterns with Entity Framework in ASP.NET Core, you create repositories for data access operations and a Unit of Work class to coordinate multiple repositories, ensuring atomic operations within a single transaction.</p>



<p class="custp1 p-mb-0"><strong>Steps:</strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li>Create Repository Interface</li>



<li>Implement Repository Class</li>



<li>Create Unit of Work Interface</li>



<li>Implement Unit of Work Class</li>



<li>Register Unit of Work in Startup.cs</li>



<li>Use Unit of Work in a Controller</li>
</ol>



<button class="shbtn" id="shbtn72119" onclick="showHideBlock(72119)">&#9660; <u>Show example</u></button>
<div id="shdiv72119" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Create Repository Interface:</b> Define a generic interface for common data operations.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">interface</span> IRepository&lt;T&gt where T : <span class="key">class</span>
{
    Task&lt;IEnumerable&lt;T&gt&gt GetAllAsync();
    Task&lt;T&gt GetByIdAsync(<span class="key">int</span> id);
    <span class="key">void</span> Add(T entity);
    <span class="key">void</span> Remove(T entity);
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Implement Repository Class:</b> Implement the IRepository interface using DbContext.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Repository&lt;T&gt : IRepository&lt;T&gt where T : <span class="key">class</span>
{
    <span class="key">private</span> <span class="key">readonly</span> AppDbContext _context;
    <span class="key">private</span> <span class="key">readonly</span> DbSet&lt;T&gt _dbSet;

    <span class="key">public</span> Repository(AppDbContext context)
    {
        _context = context;
        _dbSet = context.Set&lt;T&gt();
    }

    <span class="key">public</span> <span class="key">async</span> Task&lt;IEnumerable&lt;T&gt&gt GetAllAsync() =&gt <span class="key">await</span> _dbSet.ToListAsync();
    <span class="key">public</span> <span class="key">async</span> Task&lt;T&gt GetByIdAsync(<span class="key">int</span> id) =&gt <span class="key">await</span> _dbSet.FindAsync(id);
    <span class="key">public</span> <span class="key">void</span> Add(T entity) =&gt _dbSet.Add(entity);
    <span class="key">public</span> <span class="key">void</span> Remove(T entity) =&gt _dbSet.Remove(entity);
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>3. Create Unit of Work Interface:</b> Define an interface that includes repository properties and a Save method for committing changes.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">interface</span> IUnitOfWork
{
    IRepository&lt;Product&gt Products { get; }
    IRepository&lt;Order&gt Orders { get; }
    Task SaveAsync();
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>4. Implement Unit of Work Class:</b> Implement the IUnitOfWork interface to initialize and save multiple repositories.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> UnitOfWork : IUnitOfWork
{
    <span class="key">private</span> <span class="key">readonly</span> AppDbContext _context;
    <span class="key">public</span> IRepository&lt;Product&gt Products { get; <span class="key">private</span> set; }
    <span class="key">public</span> IRepository&lt;Order&gt Orders { get; <span class="key">private</span> set; }

    <span class="key">public</span> UnitOfWork(AppDbContext context)
    {
        _context = context;
        Products = <span class="key">new</span> Repository&lt;Product&gt(context);
        Orders = <span class="key">new</span> Repository&lt;Order&gt(context);
    }

    <span class="key">public</span> <span class="key">async</span> Task SaveAsync() =&gt <span class="key">await</span> _context.SaveChangesAsync();
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>5. Register Unit of Work in Startup.cs:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
{
    services.AddDbContext&lt;AppDbContext&gt(options =&gt options.UseSqlServer(Configuration.GetConnectionString(<span class="str">"DefaultConnection"</span>)));
    services.<span style="background:#f2f19d;">AddScoped&lt;IUnitOfWork, UnitOfWork&gt()</span>;
    services.AddControllers();
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>6. Use Unit of Work in a Controller:</b> Inject and use the IUnitOfWork to access repositories and save changes.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    <span class="key">private</span> <span class="key">readonly</span> IUnitOfWork _unitOfWork;

    <span class="key">public</span> ProductsController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    <span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt AddProduct(Product product)
    {
        _unitOfWork.Products.Add(product);
        <span class="key">await</span> _unitOfWork.SaveAsync();
        <span class="key">return</span> Ok();
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you perform database seeding during application startup in ASP.NET Core?</strong></h3>



<p class="pt20 p-mb-0">To perform database seeding during application startup in ASP.NET Core, you can seed data directly within the <strong>DbContext</strong> or within the application’s startup logic. This approach populates the database with initial data if it’s empty or needs specific default values.</p>



<p class="custp1 p-mb-0"><strong>Steps to Seed Data on Startup:</strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Create Seed Method in DbContext</strong>: Populate default data if necessary.</li>



<li><strong>Call Seed on Startup</strong>: Use <span class="spanHT">CreateScope()</span> to run the seeding method during app startup.</li>



<li><strong>Optional Use of OnModelCreating</strong>: For static data, use <span class="spanHT">HasData</span> in <span class="spanHT">OnModelCreating</span>.</li>
</ol>



<button class="shbtn" id="shbtn93589" onclick="showHideBlock(93589)">&#9660; <u>Show example</u></button>
<div id="shdiv93589" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Create a Seed Method in DbContext:</b> Define a method to add initial data in your DbContext.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> AppDbContext : DbContext
{
    <span class="key">public</span> DbSet&lt;Product&gt Products { get; set; }

    <span class="key">public</span> AppDbContext(DbContextOptions&lt;AppDbContext&gt options) : <span class="key">base</span>(options) { }

    <span class="key">public</span> <span class="key">void</span> <span style="background:#f2f19d;">Seed()</span>
    {
        <span class="key">if</span> (!Products.Any())
        {
            Products.AddRange(
                <span class="key">new</span> Product { Name = <span class="str">"Product1"</span>, Price = 100 },
                <span class="key">new</span> Product { Name = <span class="str">"Product2"</span>, Price = 200 }
            );
            SaveChanges();
        }
    }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Call Seed Method on Application Startup:</b> Use IServiceProvider to resolve the DbContext and call the Seed method during startup.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="key">var</span> host = CreateHostBuilder(args).Build();
        SeedDatabase(host);
        host.Run();
    }

    <span class="key">private</span> <span class="key">static</span> <span class="key">void</span> SeedDatabase(IHost host)
    {
        <span class="key">using</span> (<span class="key">var</span> scope = host.Services.CreateScope())
        {
            <span class="key">var</span> services = scope.ServiceProvider;
            <span class="key">var</span> context = services.GetRequiredService&lt;AppDbContext&gt();

            context.Database.Migrate(); <span class="com">// Apply migrations</span>
            <span style="background:#f2f19d;">context.Seed()</span>; <span class="com">// Seed data</span>
        }
    }

    <span class="key">public</span> <span class="key">static</span> IHostBuilder CreateHostBuilder(string[] args) =&gt
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =&gt
            {
                webBuilder.UseStartup&lt;Startup&gt();
            });
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>Alternative &#8211; Use ModelBuilder in OnModelCreating:</b> You can also use the ModelBuilder inside OnModelCreating for simpler seeding if data is not expected to change.</div>
<pre class="pchl"><code><span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity&lt;Product&gt().<span style="background:#f2f19d;">HasData</span>(
        <span class="key">new</span> Product { Id = 1, Name = <span class="str">"Product1"</span>, Price = 100 },
        <span class="key">new</span> Product { Id = 2, Name = <span class="str">"Product2"</span>, Price = 200 }
    );
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the best practices for managing DbContext lifetime in ASP.NET Core?</strong></h3>



<p class="pt20 p-mb-0">Here’s a concise list of best practices for managing DbContext lifetime in ASP.NET Core:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="pt5"><strong>Use Scoped Lifetime</strong> (Default for DbContext): Register DbContext with a scoped lifetime (one instance per request).</li>



<li class="custp1"><strong>Avoid Static Fields</strong>: DbContext isn’t thread-safe, so avoid using static/global variables.</li>



<li class="custp1"><strong>Avoid Singleton Services</strong>: Don’t inject DbContext into Singleton services; use IServiceProvider if necessary.</li>



<li class="custp1"><strong>Let DI Dispose Automatically</strong>: ASP.NET Core disposes DbContext automatically per request; avoid manual disposal.</li>



<li class="custp1"><strong>Single Request Lifetime</strong>: Limit each DbContext instance to a single request for fresh data.</li>



<li class="custp1"><strong>Separate Read/Write DbContexts</strong> (Optional): For high-traffic apps, use separate contexts for read and write operations.</li>



<li class="custp1"><strong>Configure Connection Resiliency</strong>: For SQL Server, use <span class="spanHT">EnableRetryOnFailure()</span> to handle transient errors.
<br>
<pre class="pchl" style="margin-top: 0;"><code>services.AddDbContext&lt;AppDbContext&gt;(options =&gt; 
    options.UseSqlServer(Configuration.GetConnectionString(<span class="str">"DefaultConnection"</span>), 
    sqlOptions =&gt; sqlOptions.<span style="background:#f2f19d;">EnableRetryOnFailure()</span>)); </code></pre>
</li>



<li class="custp1"><strong>Use AsNoTracking for Reads</strong>: For read-only queries, use <span class="spanHT">AsNoTracking</span> to boost performance by skipping change tracking. <br> <pre class="pchl" style="margin-top: 0;"><code><span class="key">var</span> products = <span class="key">await</span> _context.Products.<span style="background:#f2f19d;">AsNoTracking()</span>.ToListAsync(); </code></pre> </li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How can you use Entity Framework in a background service in ASP.NET Core?</strong></h3>



<p class="pt20 p-mb-0">To use Entity Framework in a background service in ASP.NET Core, inject the DbContext through a scoped dependency within the background service&#8217;s execution method. This ensures each background operation gets a fresh DbContext instance per execution cycle. This prevents DbContext lifetime issues in long-running services.</p>



<p class="custp1 p-mb-0">Use <span class="spanHT">IServiceProvider.CreateScope()</span> within <span class="spanHT">ExecuteAsync</span> to create a new scope. </p>



<button class="shbtn" id="shbtn48377" onclick="showHideBlock(48377)">&#9660; <u>Show example</u></button>
<div id="shdiv48377" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Define Background Service:</b> Implement a background service by inheriting from <span class="spanHT">BackgroundService</span>.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> MyBackgroundService : <span style="background:#f2f19d;">BackgroundService</span>
{
    <span class="key">private</span> <span class="key">readonly</span> IServiceProvider _serviceProvider;

    <span class="key">public</span> MyBackgroundService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    <span class="key">protected</span> <span class="key">override</span> <span class="key">async</span> Task ExecuteAsync(CancellationToken stoppingToken)
    {
        <span class="key">while</span> (!stoppingToken.IsCancellationRequested)
        {
            <span class="key">using</span> (<span class="key">var</span> scope = _serviceProvider.CreateScope())
            {
                <span class="key">var</span> dbContext = scope.ServiceProvider.GetRequiredService&lt;AppDbContext&gt;();
                <span class="com">// Use dbContext to interact with the database</span>
                <span class="key">var</span> data = <span class="key">await</span> dbContext.Items.ToListAsync(stoppingToken);
                <span class="com">// Process data</span>
            }

            <span class="key">await</span> Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
        }
    }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Register Background Service:</b> Add the background service to the service collection in Startup.cs or Program.cs.</div>
<pre class="pchl"><code>services.AddHostedService&lt;<span style="background:#f2f19d;">MyBackgroundService</span>&gt;();
services.AddDbContext&lt;AppDbContext&gt;(options =&gt;
    options.UseSqlServer(Configuration.GetConnectionString(<span class="str">"DefaultConnection"</span>))); </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle connection resiliency with Entity Framework Core in ASP.NET Core?</strong></h3>



<p class="pt20 p-mb-0">Configuring <span class="spanHT">EnableRetryOnFailure</span> on the <span class="spanHT">DbContext</span> provides automatic retry logic for transient errors, improving connection resiliency in ASP.NET Core applications.</p>



<p class="custp1 p-mb-0"><strong>Steps:</strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Enable Retry Logic</strong>: Use the <span class="spanHT">EnableRetryOnFailure</span> option.</li>



<li><strong>Customize Retry Policy</strong>: You can configure the maximum number of retries, delay between attempts, and specific error codes to retry, which are helpful for tuning resiliency based on your database and application needs.</li>



<li><strong>Consider Idempotent Operations</strong>: For safe retries, ensure operations are idempotent (i.e., safe to retry without side effects) to avoid unintended consequences from repeated execution.</li>
</ol>



<button class="shbtn" id="shbtn16265" onclick="showHideBlock(16265)">&#9660; <u>Show example</u></button>
<div id="shdiv16265" style="display: none;">

<pre class="pchl"><code>services.AddDbContext&lt;AppDbContext&gt;(options =&gt;
    options.UseSqlServer(Configuration.GetConnectionString(<span class="str">"DefaultConnection"</span>), 
        sqlOptions =&gt; sqlOptions.<span style="background:#f2f19d;">EnableRetryOnFailure</span>(
            <span style="background:#f2f19d;">maxRetryCount</span>: 5, <span class="com">// Maximum retry attempts</span>
            <span style="background:#f2f19d;">maxRetryDelay</span>: TimeSpan.FromSeconds(10), <span class="com"> // Delay between retries</span>
            errorNumbersToAdd: <span class="key">null</span>))); <span class="com">// Additional SQL error codes to retry</span></code></pre>

</div>



<br><br><br><br><br>



<h2 class="wp-block-heading h2Cust1"><strong>Performance Tuning and Optimization &#8211; Q &amp; A</strong></h2>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you optimize the performance of queries in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0"><strong>Short answer &#8211;</strong> Apply <span class="spanHT">AsNoTracking</span>, limit selected columns, use <span class="spanHT">Include</span> and <span class="spanHT">Where</span> efficiently, avoid early <span class="spanHT">ToList</span>, and consider compiled queries for frequently run operations. These techniques reduce memory usage and improve query speed.</p>



<p class="pt20 p-mb-0"><strong>In Detail:</strong> To optimize query performance in Entity Framework, use the following techniques:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Use &#8216;AsNoTracking&#8217; for Read-Only Queries</strong>: Disables change tracking, reducing overhead for read-only operations.
<pre class="pchl m-t-0" style="margin-top:0"><code><span class="key">var</span> customers = <span class="key">await</span> context.Customers.<span style="background:#f2f19d;">AsNoTracking()</span>.ToListAsync(); </code></pre>
</li>



<li class="pt15"><strong>Limit Data with &#8216;Select&#8217;</strong>: Retrieve only necessary columns instead of whole entities.
<pre class="pchl m-t-0" style="margin-top:0"><code><span class="key">var</span> names = <span class="key">await</span> context.Customers.<span style="background:#f2f19d;">Select</span>(c =&gt; c.Name).ToListAsync(); </code></pre>
</li>



<li class="pt15"><strong>Use &#8216;Include&#8217; Wisely</strong>: Include related data only when necessary to avoid unnecessary joins.
<pre class="pchl m-t-0" style="margin-top:0"><code><span class="key">var</span> orders = <span class="key">await</span> context.Orders.<span style="background:#f2f19d;">Include</span>(o =&gt; o.Customer).ToListAsync(); </code></pre>
</li>



<li class="pt15"><strong>Filter Early with &#8216;Where&#8217;</strong>: Apply filtering at the database level to minimize data retrieval.
<pre class="pchl m-t-0" style="margin-top:0"><code><span class="key">var</span> activeOrders = <span class="key">await</span> context.Orders.<span style="background:#f2f19d;">Where</span>(o =&gt; o.IsActive).ToListAsync(); </code></pre>
</li>



<li class="pt15"><strong>Avoid &#8216;ToList&#8217; Before Query Completion</strong>: Avoid calling <span class="spanHT">ToList</span> too early; chain queries to minimize data pulled into memory.
<pre class="pchl m-t-0" style="margin-top:0"><code><span class="key">var</span> highValueOrders = <span class="key">await</span> context.Orders
    .Where(o =&gt; o.TotalAmount &gt; 1000)
    .<span style="background:#f2f19d;">ToListAsync()</span>; </code></pre>
</li>



<li class="pt15"><strong>Use Compiled Queries for Frequent Operations</strong>: Compiled queries are pre-optimized for reuse and are faster for repeated queries.
<pre class="pchl m-t-0"><code><span class="key">private</span> <span class="key">static</span> <span class="key">readonly</span> Func&lt;AppDbContext, <span class="key">int</span>, Task&lt;Order&gt;&gt; GetOrderById =
    EF.<span style="background:#f2f19d;">CompileAsyncQuery</span>((AppDbContext context, <span class="key">int</span> orderId) =&gt; 
    context.Orders.Single(o =&gt; o.Id == orderId)); </code></pre>
</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of &#8216;AsSplitQuery&#8217; in Entity Framework Core?</strong></h3>



<p class="pt20 p-mb-0"><span class="spanHT">AsSplitQuery</span> in Entity Framework Core improves performance by splitting a single query with multiple <span class="spanHT">Include</span> statements into separate SQL queries. This prevents duplication (Cartesian explosion) in complex relationships, reduces memory usage, and can optimize query performance.</p>



<p class="pt15 p-mb-0"><strong>When to Use &#8216;AsSplitQuery&#8217;:</strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>When loading multiple related entities with <span class="spanHT">Include</span> statements (e.g., loading complex object graphs).</li>



<li>When you notice performance degradation or excessive data being returned due to large joins.</li>
</ul>



<button class="shbtn" id="shbtn18847" onclick="showHideBlock(18847)">&#9660; <u>Show example</u></button>
<div id="shdiv18847" style="display: none;">

<pre class="pchl"><code><span class="key">var</span> orders = <span class="key">await</span> context.Orders
    .Include(o =&gt o.Customer)
    .Include(o =&gt o.OrderItems)
    .<span style="background:#f2f19d;">AsSplitQuery()</span> <span class="com">// Executes multiple queries for each include</span>
    .ToListAsync(); </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How can you reduce memory usage when using Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">To reduce memory usage in Entity Framework, follow these practices:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Use &#8216;AsNoTracking&#8217; for Read-Only Queries</strong>: Disables change tracking, saving memory for read-only data. <pre class="pchl m-t-0"><code><span class="key">var</span> products = <span class="key">await</span> context.Products.<span style="background:#f2f19d;">AsNoTracking()</span>.ToListAsync(); </code></pre> </li>



<li class="pt15"><strong>Limit Fetched Columns with &#8216;Select&#8217;</strong>: Retrieve only necessary columns to minimize data loading.
<pre class="pchl m-t-0"><code><span class="key">var</span> names = <span class="key">await</span> context.Customers.<span style="background:#f2f19d;">Select(c =&gt; c.Name)</span>.ToListAsync(); </code></pre>
</li>



<li class="pt15"><strong>Use &#8216;AsSplitQuery&#8217; for Complex Queries</strong>: Splits large joins into multiple queries, reducing memory from duplicated data.
<pre class="pchl m-t-0"><code><span class="key">var</span> orders = <span class="key">await</span> context.Orders
    .Include(o =&gt; o.Items)
    .<span style="background:#f2f19d;">AsSplitQuery()</span>
    .ToListAsync(); </code></pre>
</li>



<li class="pt15"><strong>Retrieve Data in Batches with &#8216;Take&#8217;</strong>: Load data in smaller chunks to avoid loading large datasets all at once.
<pre class="pchl m-t-0"><code><span class="key">var</span> batch = <span class="key">await</span> context.Orders.<span style="background:#f2f19d;">Take(100)</span>.ToListAsync(); </code></pre>
</li>



<li class="pt15"><strong>Dispose &#8216;DbContext&#8217; Correctly</strong>: Use a new <span class="spanHT">DbContext</span> per operation to prevent memory leaks.</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How does the &#8216;FromSqlRaw&#8217; method differ from &#8216;FromSqlInterpolated&#8217;?</strong></h3>



<p class="pt20 p-mb-0">The <strong>FromSqlRaw</strong> and <strong>FromSqlInterpolated</strong> methods are used to execute raw SQL queries. </p>



<p class="custp1 p-mb-0"><span class="spanHT">FromSqlRaw</span> requires manual parameter passing, while <span class="spanHT">FromSqlInterpolated</span> handles parameters automatically in interpolated strings, reducing the risk of SQL injection.</p>



<p class="pt15 p-mb-0"><strong>1. FromSqlRaw</strong>: Executes a raw SQL query with parameters that must be explicitly passed to prevent SQL injection. Use this for predefined SQL strings.</p>



<pre class="pchl m-t-0"><code><span class="key">var</span> customers = context.Customers
    .<span style="background:#f2f19d;">FromSqlRaw</span>(<span class="str">"SELECT * FROM Customers WHERE City = {0}"</span>, city)
    .ToList(); </code></pre>



<p class="pt20 p-mb-0"><strong>2. FromSqlInterpolated</strong>: Executes an interpolated SQL query, where parameters are automatically handled within the interpolated string, making it easier and safer to use with inline variables.</p>



<pre class="pchl m-t-0"><code><span class="key">var</span> customers = context.Customers
    .<span style="background:#f2f19d;">FromSqlInterpolated</span>($<span class="str">"SELECT * FROM Customers WHERE City = {city}"</span>)
    .ToList(); </code></pre>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the &#8216;BatchSize&#8217; parameter in EF?</strong></h3>



<p class="pt20 p-mb-0">The <span class="spanHT">BatchSize</span> parameter in Entity Framework limits the number of commands sent in a single batch during <span class="spanHT">SaveChanges</span>. This improves performance in bulk operations by reducing database round-trips and helps avoid timeouts or memory issues.</p>



<pre class="pchl"><code>optionsBuilder.UseSqlServer(connectionString, options =&gt; options.<span style="background:#f2f19d;">MaxBatchSize(100)</span>); </code></pre>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle large data sets in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">Use these strategies to handle large data sets in EF efficiently:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Paging with &#8216;Skip&#8217; and &#8216;Take&#8217;</strong>: Load data in smaller, manageable chunks. <pre class="pchl m-t-0"><code><span class="key">var</span> batch = <span class="key">await</span> context.Items.<span style="background:#f2f19d;">Skip</span>(0).<span style="background:#f2f19d;">Take</span>(100).ToListAsync(); </code></pre> </li>



<li class="pt15"><strong>Use &#8216;AsNoTracking&#8217; for Read-Only Data</strong>: Disables change tracking, reducing memory usage. <pre class="pchl m-t-0"><code><span class="key">var</span> data = <span class="key">await</span> context.LargeDataSet.<span style="background:#f2f19d;">AsNoTracking()</span>.ToListAsync(); </code></pre> </li>



<li class="pt15"><strong>Filter Early with &#8216;Where&#8217;</strong>: Apply filters to reduce the amount of data retrieved. <pre class="pchl m-t-0"><code><span class="key">var</span> filteredData = <span class="key">await</span> context.Items.<span style="background:#f2f19d;">Where</span>(i =&gt; i.IsActive).ToListAsync(); </code></pre> </li>



<li class="pt15"><strong>Batch Processing for Bulk Operations</strong>: Use <span class="spanHT">BatchSize</span> to process data in batches, minimizing round-trips.
<pre class="pchl m-t-0"><code>optionsBuilder.UseSqlServer(connectionString, options =&gt; options.<span style="background:#f2f19d;">MaxBatchSize(100)</span>); </code></pre>
</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How does Entity Framework handle caching?</strong></h3>



<p class="pt20 p-mb-0">Entity Framework uses <strong>first-level caching</strong> by default, which caches entities within the scope of a single <span class="spanHT">DbContext</span> instance. When you query for an entity, EF checks the context cache first before querying the database. This helps reduce duplicate database calls within the same context.</p>



<button class="shbtn" id="shbtn21977" onclick="showHideBlock(21977)">&#9660; <u>Show example</u></button>
<div id="shdiv21977" style="display: none;" class="shdt">

<pre class="pchl"><code><span class="key">using</span> (<span class="key">var</span> context = <span class="key">new</span> AppDbContext())
{
    <span class="key">var</span> product1 = <span class="key">await</span> context.Products.FindAsync(1); <span class="com">// Database call</span>
    <span class="key">var</span> product2 = <span class="key">await</span> context.Products.FindAsync(1); <span class="com">// Retrieved from cache (no DB call)</span>
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">In this example, <span class="spanHT">product2</span> is fetched from the <span class="spanHT">DbContext</span> cache, avoiding a second database call. Note that the cache only lasts as long as the <span class="spanHT">DbContext</span> instance.</div>
<br>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is &#8216;CompiledQuery&#8217; in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">A <strong>CompiledQuery</strong> in Entity Framework is a pre-compiled LINQ query that improves performance by reusing the query execution plan. This is useful for queries that are frequently executed, as it avoids the overhead of re-compiling the query each time.</p>



<button class="shbtn" id="shbtn64039" onclick="showHideBlock(64039)">&#9660; <u>Show example</u></button>
<div id="shdiv64039" style="display: none;" class="shdt">

<pre class="pchl"><code><span class="key">private</span> <span class="key">static</span> <span class="key">readonly</span> Func&lt;AppDbContext, <span class="key">int</span>, Task&lt;Product&gt;&gt; GetProductById =
    EF.CompileAsyncQuery((AppDbContext context, <span class="key">int</span> id) =&gt; 
        context.Products.Single(p =&gt; p.Id == id));

<span class="key">var</span> product = <span class="key">await</span> GetProductById(context, 1); <span class="com">// Executes using the compiled query</span></code></pre>

<br>
<div style="padding-left: 0.3125rem;">Here, <b>GetProductById</b> is a compiled query that retrieves a product by ID, improving performance for repeated executions of this query.
</div>
<br>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use a connection pool with Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">Entity Framework Core uses <strong>connection pooling</strong> automatically when configured with a database provider that supports it (e.g., SQL Server). Connection pooling allows multiple <strong>DbContext</strong> instances to reuse connections, reducing the overhead of opening and closing database connections.</p>



<p class="custp1 p-mb-0">connection pooling is enabled by default, so simply configuring the connection string with DbContext automatically uses it:</p>



<pre class="pchl"><code>services.AddDbContext&lt;AppDbContext&gt(options =&gt
    options.UseSqlServer(<span class="str">"YourConnectionString"</span>)); </code></pre>



<p class="custp1 p-mb-0">No additional configuration is needed to enable pooling; however, you can control pool size with certain providers if needed. Connection pooling improves performance by managing connection reuse internally.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you monitor and profile the performance of Entity Framework queries?</strong></h3>



<p class="pt20 p-mb-0">To monitor and profile the performance of Entity Framework queries, you can use the following methods:</p>



<ul class="ol1 ol1-mb--0 wp-block-list">
<li class="custp1"><strong>Enable Logging</strong>: Use ASP.NET Core’s built-in logging to capture SQL queries and execution details.
<pre class="pchl m-t-0"><code>services.AddDbContext&lt;AppDbContext&gt;(options =&gt;
    options.UseSqlServer(<span class="str">"YourConnectionString"</span>)
           .EnableSensitiveDataLogging() <span class="com">// Optional: shows parameter values</span>
           .<span style="background:#f2f19d;">LogTo(Console.WriteLine)</span>);    <span class="com">// Logs to the console</span>
</code></pre>
</li>



<li class="pt15"><strong>Use <span class="spanHT">Microsoft.EntityFrameworkCore.Diagnostics</span> Events</strong>: Monitor EF Core events for detailed query insights by subscribing to diagnostic events.</li>



<li class="pt5"><strong>Third-Party Profiling Tools</strong>: Tools like <strong>MiniProfiler</strong>, <strong>EF Core Profiler</strong>, or <strong>SQL Server Profiler</strong> provide detailed insights into query execution time, frequency, and optimization opportunities.</li>



<li class="pt5"><strong>Query Execution Plans</strong>: Review SQL execution plans in SQL Server Management Studio (SSMS) to understand how queries are processed and identify potential improvements.</li>



<li class="pt5"><strong>Performance Counters and Application Insights</strong>: For production environments, use Application Insights or performance counters to track EF Core performance and detect bottlenecks.</li>
</ul>



<br><br><br><br>



<h2 class="wp-block-heading h2Cust1"><strong>EF Core Features &amp; Others &#8211; Q &amp; A</strong></h2>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the &#8216;HasQueryFilter&#8217; method used for?</strong></h3>



<p class="pt20 p-mb-0">The <span class="spanHT">HasQueryFilter</span> method defines a <strong>global filter</strong> for entities, automatically applying a condition to all queries for that entity type. This is useful for soft deletes, multi-tenancy, and other scenarios requiring consistent filtering.</p>



<button class="shbtn" id="shbtn6639" onclick="showHideBlock(6639)">&#9660; <u>Show example</u></button>
<div id="shdiv6639" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Example:</b> To filter out soft-deleted records, you can apply a query filter on the <span class="spanHT">IsDeleted</span> property:</div>

<pre class="pchl"><code>modelBuilder.Entity&lt;Product&gt;()
    .HasQueryFilter(p =&gt; !p.IsDeleted); </code></pre>

<br>
<div style="padding-left: 0.3125rem;">With this filter, all queries on <b>Product</b> will automatically exclude records where <b>IsDeleted</b> is true, unless explicitly overridden.</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How does EF Core support &#8216;spatial data&#8217; types?</strong></h3>



<p class="pt20 p-mb-0"><strong>Spatial data types</strong> are specialized data types used to store geometric and geographic information, such as points, lines, and polygons, representing real-world locations. These data types are often used for mapping, geographic information systems (GIS), and location-based services.</p>



<p class="custp1 p-mb-0">Entity Framework Core supports spatial data types using <span class="spanHT">NetTopologySuite</span>, allowing storage and querying of geographic data like points and polygons.</p>



<button class="shbtn" id="shbtn23146" onclick="showHideBlock(23146)">&#9660; <u>Show example</u></button>
<div id="shdiv23146" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1.</b> To use spatial data types, first install <b>NetTopologySuite</b>:</div>
<div style="background-color: #000; color: #fff; padding: 15px; margin-top:5px;">dotnet add package Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite
</div>

<br>
<div style="padding-left: 0.3125rem;"><b>2.</b> Then, configure the <b>DbContext</b> to use <b>NetTopologySuite</b>:</div>
<pre class="pchl"><code>services.AddDbContext&lt;AppDbContext&gt(options =&gt;
    options.UseSqlServer(<span class="str">"YourConnectionString"</span>, sqlOptions =&gt;
        sqlOptions.UseNetTopologySuite())); </code></pre>

<br>
<div style="padding-left: 0.3125rem;"><b>3.</b> Define an entity with a spatial property, like <b>Point</b>:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Location
{
    <span class="key">public</span> <span class="key">int</span> Id { get; set; }
    <span class="key">public</span> Point Coordinates { get; set; } <span class="com">// Point is a spatial data type</span>
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">This setup allows EF Core to store and query spatial data, such as finding entities within a certain distance or area.</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the &#8216;ToView&#8217; method in Entity Framework Core?</strong></h3>



<p class="pt20 p-mb-0">The <span class="spanHT">ToView</span> method maps an entity to a <strong>database view</strong> rather than a table. It is used when you want to query a view but not allow modifications, as views are typically read-only in EF Core.</p>



<p class="custp1 p-mb-0"><strong>Example:</strong> If you have a view called <strong>ActiveProducts</strong> in your database, you can map it to an entity:</p>



<pre class="pchl" style="margin-top:5px;"><code>modelBuilder.Entity&lt;Product&gt()
    .ToView(<span class="str">"ActiveProducts"</span>); </code></pre>



<p class="custp1 p-mb-0">Here, <strong>Product</strong> will be mapped to the <strong>ActiveProducts</strong> view, allowing you to run queries on it while preventing insert, update, or delete operations.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed">What is &#8216;Keyless Entity Type&#8217; in EF Core?</h3>



<p class="pt20 p-mb-0">A <strong>Keyless Entity Type</strong> is an entity that does not have a primary key. (Earlier it is called &#8216;Query Types&#8217;.) It&#8217;s useful for mapping database views, raw SQL queries, or other read-only data structures where a primary key isn&#8217;t needed. </p>



<button class="shbtn" id="shbtn53865" onclick="showHideBlock(53865)">&#9660; <u>Show example</u></button>
<div id="shdiv53865" style="display: none;" class="shdt">
<br>
<div style="padding-left: 0.3125rem;"><b>1.</b></div>
<pre class="pchl m-t-0"><code><span class="key">public</span> <span class="key">class</span> <b>SalesReport</b>
{
    <span class="key">public</span> <span class="key">string</span> ProductName { get; set; }
    <span class="key">public</span> <span class="key">int</span> TotalSales { get; set; }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;"><b>2.</b></div>
<pre class="pchl m-t-0"><code>modelBuilder.Entity&lt;<b>SalesReport</b>&gt;().<span style="background:#f2f19d;">HasNoKey()</span>; </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle enum types in EF Core?</strong></h3>



<p class="pt20 p-mb-0">Entity Framework Core supports <strong>enum types</strong> by mapping them to their underlying integer values in the database. You can use enums directly in entity classes, and EF Core will handle conversion automatically.</p>



<button class="shbtn" id="shbtn98740" onclick="showHideBlock(98740)">&#9660; <u>Show example</u></button>
<div id="shdiv98740" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1.</b> Define an enum and use it in an entity:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">enum</span> OrderStatus
{
    Pending,
    Shipped,
    Delivered
}

<span class="key">public</span> <span class="key">class</span> Order
{
    <span class="key">public</span> <span class="key">int</span> Id { get; set; }
    <span class="key">public</span> OrderStatus Status { get; set; } <span class="com">// Enum property</span>
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;"><b>2.</b> EF Core will store the &#39;Status&#39; property as an integer in the database, corresponding to the enum&#8217;s values. You can query using the enum directly:</div>
<pre class="pchl"><code><span class="key">var</span> Orders = context.Orders
			.Where(o =&gt o.Status == OrderStatus.Shipped)
			.ToList(); </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Interceptors in EF Core, and how are they used?</strong></h3>



<p class="pt20 p-mb-0"><strong>Interceptors</strong> are components that allow you to intercept and modify operations like database commands, queries, and save actions before they are executed. They’re useful for logging, auditing, and custom validation.</p>



<button class="shbtn" id="shbtn17352" onclick="showHideBlock(17352)">&#9660; <u>Show example</u></button>
<div id="shdiv17352" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;">To create a command interceptor for logging SQL commands:
<br><br>
<b>1. Implement <span class="spanHT">IDbCommandInterceptor</span>:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> MyCommandInterceptor : <span style="background:#f2f19d;">DbCommandInterceptor</span>
{
    <span class="key">public</span> <span class="key">override</span> InterceptionResult&lt;<span class="key">int</span>&gt NonQueryExecuting(DbCommand command, CommandEventData eventData, InterceptionResult&lt;<span class="key">int</span>&gt result)
    {
        Console.WriteLine($<span class="str">"Executing Command: {command.CommandText}"</span>);
        <span class="key">return</span> base.NonQueryExecuting(command, eventData, result);
    }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;"><b>2. Register the interceptor in DbContext:</b></div>
<pre class="pchl"><code><span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .<span style="background:#f2f19d;">AddInterceptors</span>(<span class="key">new</span> MyCommandInterceptor())
        .UseSqlServer(<span class="str">"YourConnectionString"</span>);
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">With this setup, the interceptor logs every SQL command before it’s executed. Interceptors provide flexible ways to hook into EF Core&#8217;s data pipeline for additional functionality.</div>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use Value Conversions in EF Core?</strong></h3>



<p class="pt20 p-mb-0"><strong>Value Conversions</strong> in Entity Framework Core are used to convert property values between the entity and the database format, allowing you to store complex types, enums, or custom data formats as simpler database types.</p>



<button class="shbtn" id="shbtn21223" onclick="showHideBlock(21223)">&#9660; <u>Show example</u></button>
<div id="shdiv21223" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;">To store an enum as a string in the database:</div>


<br>
<div style="padding-left: 0.3125rem;"><b>1.</b> Define the enum and the entity:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">enum</span> PriorityLevel
{
    Low,
    Medium,
    High
}

<span class="key">public</span> <span class="key">class</span> Task
{
    <span class="key">public</span> <span class="key">int</span> Id { get; set; }
    <span class="key">public</span> PriorityLevel Priority { get; set; } <span class="com">// Enum property</span>
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2.</b> Configure the value converter in &#39;OnModelCreating&#39;:</div>
<pre class="pchl"><code><span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity&lt;Task&gt()
        .Property(t =&gt t.Priority)
        .<span style="background:#f2f19d;">HasConversion</span>&lt;<span class="key">string</span>&gt(); <span class="com">// Stores enum as string</span>
} </code></pre>


<br>
<div style="padding-left: 0.3125rem;">This setup saves the &#39;Priority&#39; enum as a string (e.g., &#8220;Low&#8221;, &#8220;Medium&#8221;) in the database, instead of the default integer. Value conversions provide flexibility in how data is stored and retrieved in EF Core.</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are backing fields, and how are they used in EF Core?</strong></h3>



<p class="pt20 p-mb-0"><strong>Backing fields</strong> in Entity Framework Core are private fields used to store data for a property, typically when you want to control how the property is accessed or modified. They’re useful for encapsulation or when you need custom logic in getters and setters without exposing the underlying field directly.</p>



<button class="shbtn" id="shbtn80244" onclick="showHideBlock(80244)">&#9660; <u>Show example</u></button>
<div id="shdiv80244" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1.</b> Define a backing field for a property in an entity:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    <span class="key">private</span> <span class="key">decimal</span> _price;

    <span class="key">public</span> <span class="key">int</span> Id { get; set; }
    <span class="key">public</span> <span class="key">decimal</span> Price
    {
        <span class="key">get</span> =&gt _price;
        <span class="key">set</span> =&gt _price = value &gt 0 ? value : <span class="key">throw</span> <span class="key">new</span> ArgumentException(<span class="str">"Price must be positive"</span>);
    }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2.</b> In OnModelCreating, configure EF Core to use the backing field:</div>
<pre class="pchl"><code>modelBuilder.Entity&lt;Product&gt()
    .Property(p =&gt p.Price)
    .HasField(<span class="str">"_price"</span>); </code></pre>

<br>
<div style="padding-left: 0.3125rem;">Here, <b>_price</b> is a backing field for <b>Price</b>, allowing EF Core to access <b>_price</b> directly for database operations while using the custom logic in <b>Price</b>.</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement audit logging in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">To implement <strong>audit logging</strong> in Entity Framework, you can override the <span class="spanHT">SaveChanges</span> method to track changes and log them before they’re saved to the database. This is useful for recording data changes, timestamps, and users for audit purposes.</p>



<button class="shbtn" id="shbtn10023" onclick="showHideBlock(10023)">&#9660; <u>Show example</u></button>
<div id="shdiv10023" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1.</b> Add &#39;CreatedAt&#39; and &#39;UpdatedAt&#39; properties to track timestamps:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> EntityBase
{
    <span class="key">public</span> DateTime CreatedAt { get; set; }
    <span class="key">public</span> DateTime? UpdatedAt { get; set; }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2.</b> Override &#39;SaveChanges&#39; in &#39;DbContext&#39;:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">override</span> <span class="key">int</span> SaveChanges()
{
    <span class="key">var</span> entries = ChangeTracker.Entries()
        .Where(e =&gt; e.Entity <span class="key">is</span> EntityBase && (e.State == EntityState.Added || e.State == EntityState.Modified));

    <span class="key">foreach</span> (<span class="key">var</span> entry <span class="key">in</span> entries)
    {
        <span class="key">var</span> entity = (EntityBase)entry.Entity;
        entity.UpdatedAt = DateTime.Now;

        <span class="key">if</span> (entry.State == EntityState.Added)
        {
            entity.CreatedAt = DateTime.Now;
        }
    }

    <span class="key">return</span> base.SaveChanges();
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">In this example, &#39;SaveChanges&#39; updates &#39;CreatedAt&#39; for new entities and &#39;UpdatedAt&#39; for modified entities, logging the timestamps automatically. You can expand this logic to log user IDs, change history, or more complex audit details.</div>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the security considerations when using Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">The following are the key security considerations:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="pt5"><strong>SQL Injection Prevention</strong>: Use parameterized queries or LINQ to avoid SQL injection. Avoid concatenating raw SQL strings.
<pre class="pchl m-t-0"><code><span class="key">var</span> user = context.Users.FirstOrDefault(u =&gt; u.Username == username); </code></pre>
</li>



<li class="pt15"><strong>Sensitive Data Protection</strong>: Enable <strong>encryption</strong> for sensitive fields and use <strong>SecureString</strong> for in-memory sensitive data. Avoid exposing sensitive data in logs.</li>



<li class="pt5"><strong>Restricting Permissions</strong>: Limit database access permissions based on the principle of least privilege; only grant necessary CRUD operations.</li>



<li class="pt5"><strong>Proper Exception Handling</strong>: Catch and handle exceptions to avoid leaking sensitive error details in logs or UI responses.</li>



<li class="pt5"><strong>Use AsNoTracking</strong>: For read-only data, use &#8216;AsNoTracking()&#8217; to prevent potential unintended modifications and reduce memory usage. <pre class="pchl m-t-0"><code><span class="key">var</span> products = context.Products.AsNoTracking().ToList(); </code></pre></li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the &#8216;NoTracking&#8217; query used for in EF?</strong></h3>



<p class="pt20 p-mb-0">A <strong>NoTracking</strong> query retrieves data without tracking changes to the entities, meaning Entity Framework won’t monitor or cache these objects. This improves performance and memory usage for read-only operations.</p>



<pre class="pchl m-t-5"><code><span class="key">var</span> products = context.Products<span style="background:#f2f19d;">.AsNoTracking()</span>.ToList(); </code></pre>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How can you disable a migration in EF?</strong></h3>



<p class="pt20 p-mb-0">To <strong>disable a migration</strong> in Entity Framework, you can either remove it or skip applying it.</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="pt5"><strong>Remove Migration</strong>: If the migration has not yet been applied to the database, use the <span class="spanHT">Remove-Migration</span> command in the Package Manager Console:
<div class="m-t-5" style="background-color: #000; color: #fff; padding: 5px 15px;">Remove-Migration</div>
</li>



<li class="custp1"><strong>Skip Applying Migration</strong>: If the migration has already been applied, update the database to a previous migration, or delete it manually from the <span class="spanHT">__EFMigrationsHistory</span> table in the database. Then, remove the migration file from the project to avoid it being re-applied.</li>
</ul>



<p class="custp1 p-mb-0">These methods prevent the migration from being applied or re-applied in future updates.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you test Entity Framework code?</strong></h3>



<p class="pt20 p-mb-0">To <strong>test Entity Framework code</strong>, you can use <strong>in-memory databases</strong> or a <strong>mocking framework</strong> to simulate a real database without persisting data.</p>



<p class="custp1 p-mb-0"><strong>Example</strong> &#8211; Using the <span class="spanHT">InMemory</span> provider allows testing of EF Core operations without a physical database:</p>



<pre class="pchl"><code><span class="key">var</span> options = <span class="key">new</span> DbContextOptionsBuilder&lt;AppDbContext&gt()
    <span style="background:#f2f19d;">.UseInMemoryDatabase(databaseName: <span class="str">"TestDatabase"</span>)</span>
    .Options;

<span class="key">using</span> <span class="key">var</span> context = <span class="key">new</span> AppDbContext(options);
context.Products.Add(<span class="key">new</span> Product { Name = <span class="str">"Test Product"</span> });
context.SaveChanges();

<span class="key">var</span> product = context.Products.FirstOrDefault();
Assert.Equal(<span class="str">"Test Product"</span>, product.Name); </code></pre>



<p class="custp1 p-mb-0"><span class="spanHT">UseInMemoryDatabase</span> creates a temporary, in-memory database that can be used to test CRUD operations and EF Core logic. This approach is efficient for unit tests, as it avoids external dependencies.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you configure Entity Framework for SQL Server in a .NET Core application?</strong></h3>



<p class="pt20 p-mb-0">To configure <strong>Entity Framework for SQL Server</strong> in a .NET Core application, you use the <span class="spanHT">UseSqlServer</span> method in the <span class="spanHT">DbContext</span> configuration, typically in Startup.cs or in the Program.cs file.</p>



<button class="shbtn" id="shbtn12733" onclick="showHideBlock(12733)">&#9660; <u>Show example</u></button>
<div id="shdiv12733" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1.</b> Install the SQL Server provider for EF Core:</div>
<pre class="pchl"><code>dotnet add package Microsoft.EntityFrameworkCore.SqlServer </code></pre>

<br>
<div style="padding-left: 0.3125rem;"><b>2.</b> Configure DbContext in Program.cs:</div>
<pre class="pchl"><code>services.AddDbContext&lt;AppDbContext&gt(options =&gt
    options.UseSqlServer(<span class="str">"YourConnectionString"</span>)); </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement custom conventions in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">To implement <strong>custom conventions</strong> in Entity Framework Core, you use the OnModelCreating method to define rules that apply to entity properties or configurations globally.</p>



<p class="custp1 p-mb-0"><strong>Example &#8211;</strong> To create a custom convention that adds a prefix to all table names:</p>



<pre class="pchl"><code><span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(ModelBuilder modelBuilder)
{
    <span class="key">foreach</span> (<span class="key">var</span> entity <span class="key">in</span> modelBuilder.Model.GetEntityTypes())
    {
        entity.SetTableName(<span class="str">"tbl_"</span> + entity.GetTableName());
    }
} </code></pre>



<p class="custp1 p-mb-0">The custom convention prefixes each table name with &#8220;<strong>tbl_</strong>&#8220;. Custom conventions help enforce consistent rules across all entities without repetitive code.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the different lifecycle methods available in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">In Entity Framework, <strong>lifecycle methods</strong> allow you to customize behavior at various stages of the entity lifecycle. Key lifecycle methods include:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>OnModelCreating</strong>: Called when the model is being created, allowing configuration of entity relationships, conventions, and more.
<pre class="pchl m-t-5"><code><span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(ModelBuilder modelBuilder)
{
    <span class="com">// Configure entity properties, relationships</span>
} </code></pre>
</li>



<li class="pt15"><strong>SaveChanges / SaveChangesAsync</strong>: Called before data is saved to the database. You can override these to add custom logic, such as audit logging.
<pre class="pchl m-t-5"><code><span class="key">public</span> <span class="key">override</span> <span class="key">int</span> SaveChanges()
{
    <span class="com">// Custom logic before saving</span>
    <span class="key">return</span> base.SaveChanges();
} </code></pre>
</li>



<li class="pt15"><strong>OnConfiguring</strong>: Allows configuration of <strong>DbContext</strong> options, like specifying the database provider and connection string.
<pre class="pchl m-t-0"><code><span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(<span class="str">"YourConnectionString"</span>);
} </code></pre>
</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you configure default schema in EF?</strong></h3>



<p class="pt20 p-mb-0">Specify <strong>OnModelCreating</strong> method in <strong>DbContext</strong>, this sets a default schema for all tables in the context.</p>



<p class="custp1 p-mb-0"><strong>Example &#8211;</strong> To set the schema to <strong>sales</strong>:</p>



<pre class="pchl"><code><span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasDefaultSchema(<span class="str">"sales"</span>);
} </code></pre>



<p class="custp1 p-mb-0">With this configuration, EF Core will create all tables under the <strong>sales</strong> schema unless overridden for individual entities.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the various logging providers available for Entity Framework Core?</strong></h3>



<p class="pt20 p-mb-0">Entity Framework Core supports several <strong>logging providers</strong> for capturing database operations and performance metrics. Common logging providers include:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Console Logger</strong>: Logs directly to the console, useful for development and debugging.
<pre class="pchl m-t-5"><code>optionsBuilder.UseSqlServer(<span class="str">"YourConnectionString"</span>)
              .LogTo(Console.WriteLine); </code></pre>
</li>



<li class="pt15"><strong>Debug Logger</strong>: Logs to the Output window in Visual Studio, ideal for debugging.
<pre class="pchl m-t-5"><code>optionsBuilder.UseSqlServer(<span class="str">"YourConnectionString"</span>)
              .LogTo(Debug.WriteLine); </code></pre>
</li>



<li class="pt15"><strong>Third-Party Providers</strong>: Supports popular logging frameworks like <strong>Serilog</strong>, <strong>NLog</strong>, and <strong>Log4Net</strong> by configuring them in Program.cs or Startup.cs.</li>



<li class="pt15"><strong>Application Insights</strong>: Used for monitoring in production environments, especially in Azure-based applications.</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you enforce a unique constraint in EF?</strong></h3>



<p class="pt20 p-mb-0">To enforce a <strong>unique constraint</strong> in Entity Framework Core, you use the <span class="spanHT">HasIndex</span> method with the <span class="spanHT">IsUnique</span> option in the <span class="spanHT">OnModelCreating</span> method.</p>



<p class="custp1 p-mb-0"><strong>Example &#8211;</strong> To enforce a unique constraint on the Email property of a <strong>User</strong> entity:</p>



<pre class="pchl"><code><span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity&lt;User&gt;()
        .<span style="background:#f2f19d;">HasIndex</span>(u =&gt; u.Email)
        .<span style="background:#f2f19d;">IsUnique</span>();
} </code></pre>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you manage multi-tenancy with Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">To manage <strong>multi-tenancy</strong> in Entity Framework Core, you typically use a <strong>global query filter</strong> to restrict data access by tenant ID. This approach filters records by a tenant identifier, allowing each tenant to only access their own data.</p>



<button class="shbtn" id="shbtn34447" onclick="showHideBlock(34447)">&#9660; <u>Show example</u></button>
<div id="shdiv34447" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1.</b> Add a TenantId property to each entity:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Order
{
    <span class="key">public</span> <span class="key">int</span> Id { get; set; }
    <span class="key">public</span> <span class="key">int</span> TenantId { get; set; }
    <span class="key">public</span> <span class="key">string</span> ProductName { get; set; }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2.</b> Configure a global query filter in OnModelCreating:</div>
<pre class="pchl"><code><span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity&lt;Order&gt;()
        .HasQueryFilter(o =&gt; o.TenantId == _currentTenantId);
} </code></pre>


<br>
<div style="padding-left: 0.3125rem;">Here, <b>_currentTenantId</b> represents the tenant context, which you can inject or retrieve based on the user&#8217;s session. This filter ensures that all queries automatically include the tenant condition, enforcing data isolation between tenants.</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you migrate an existing application to EF Core?</strong></h3>



<p class="pt20 p-mb-0">To <strong>migrate an existing application</strong> to Entity Framework Core, you need to follow these main steps:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Install EF Core Packages</strong>: Add the EF Core packages specific to your database provider (e.g., Microsoft.EntityFrameworkCore.SqlServer).
<div class="pt10" style="background-color: #000; color: #fff; padding: 5px 15px;">dotnet add package Microsoft.EntityFrameworkCore.SqlServer
</div>
</li>



<li class="pt15"><strong>Create a DbContext</strong>: Define a new DbContext class that represents your database and includes DbSets for each entity.
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> AppDbContext : DbContext
{
    <span class="key">public</span> DbSet&lt;Customer&gt; Customers { get; set; }
    <span class="com">// other DbSets</span>

    <span class="key">protected</span> <span class="key">override</span> <span class="key">void</span> OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer(<span class="str">"YourConnectionString"</span>);
    }
} </code></pre>
</li>



<li class="pt15"><strong>Define Models</strong>: Create or update entity classes that match your existing database schema.</li>



<li class="pt15"><strong>Run Initial Migration</strong>: Generate an initial migration based on your existing schema without applying it to the database.
<div class="pt10" style="background-color: #000; color: #fff; padding: 5px 15px;">dotnet ef migrations add InitialMigration &#8211;context AppDbContext</div>
</li>



<li class="pt15"><strong>Map Existing Tables</strong>: Use <span class="spanHT">HasNoKey</span>, <span class="spanHT">HasColumnName</span>, or <span class="spanHT">HasTable</span> in <strong>OnModelCreating</strong> to map entities to existing tables without modifying their structure.</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the advantages and disadvantages of using Entity Framework?</strong></h3>



<p class="pt20 p-mb-0"><strong>Advantages</strong>:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Productivity:</strong> Automates database operations, reducing manual SQL coding.</li>



<li><strong>Change Tracking:</strong> Automatically tracks entity changes, simplifying update processes.</li>



<li><strong>Database Independence:</strong> Supports multiple database providers, enabling easy switching.</li>



<li><strong>Automatic Migrations:</strong> Handles schema changes and data migrations efficiently.</li>



<li><strong>Strongly Typed:</strong> Provides compile-time validation for queries, reducing runtime errors.</li>
</ul>



<p class="pt20 p-mb-0"><strong>Disadvantages:</strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Performance Overhead:</strong> Slower than raw SQL for complex queries or large datasets.</li>



<li><strong>Less Control:</strong> Limited fine-tuning options compared to direct SQL, especially in complex queries.</li>



<li><strong>Learning Curve:</strong> Requires understanding of LINQ, EF configuration, and model relationships.</li>



<li><strong>Debugging Complexity:</strong> Issues can be harder to troubleshoot due to abstraction layers.</li>



<li><strong>Memory Usage:</strong> High memory usage with large datasets due to change tracking and caching.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are some common pitfalls when using Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">Here are some common pitfalls when using Entity Framework:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Unintended Lazy Loading:</strong> Lazy loading can result in many small queries (N+1 problem), impacting performance when loading related data.</li>



<li><strong>Large Data Loads:</strong> Loading too much data at once can cause high memory usage and slow query performance.</li>



<li><strong>Lack of AsNoTracking:</strong> Not using AsNoTracking for read-only queries can lead to unnecessary tracking, increasing memory usage.</li>



<li><strong>Inefficient Queries:</strong> Complex LINQ queries may translate poorly to SQL, resulting in suboptimal database performance.</li>



<li><strong>Ignoring Transactions:</strong> Entity Framework handles transactions by default, but complex operations may require explicit transaction management.</li>



<li><strong>Overusing SaveChanges:</strong> Calling SaveChanges too frequently can result in multiple database trips; batch operations when possible.</li>



<li><strong>Migrations Mismanagement:</strong> Incorrect migration handling can lead to schema drift or migration conflicts, especially in teams.</li>



<li><strong>Not Handling Concurrency:</strong> Ignoring concurrency configurations may lead to data conflicts and unexpected overwrites in multi-user environments.</li>
</ol>



<p class="custp1 p-mb-0">Avoiding these pitfalls can help maintain good performance, stability, and scalability when working with Entity Framework.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How can you optimize performance in Entity Framework?</strong></h3>



<p class="pt20 p-mb-0">To optimize performance in Entity Framework, consider these strategies:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Use AsNoTracking</strong>: For read-only queries, disable change tracking to reduce memory usage.
<br>
<div style="background-color: #000; color: #fff; padding: 15px;">var products = context.Products.AsNoTracking().ToList();
</div>
</li>



<li class="custp1"><strong>Limit Data with Projections</strong>: Select only required fields using <span class="spanHT">.Select()</span> to reduce data load.
<br>
<div style="background-color: #000; color: #fff; padding: 15px;">var productNames = context.Products.Select(p =&gt; p.Name).ToList();
</div>
</li>



<li class="custp1"><strong>Batch Operations</strong>: Minimize <span class="spanHT">SaveChanges</span> calls by batching multiple updates in a single transaction.</li>



<li class="custp1"><strong>Eager Loading</strong>: Use <span class="spanHT">.Include()</span> to load related data in a single query rather than multiple queries.
<br>
<div style="background-color: #000; color: #fff; padding: 15px;">var orders = context.Orders.Include(o =&gt; o.Customer).ToList();
</div>
</li>



<li class="custp1"><strong>Use Compiled Queries</strong>: Pre-compile frequently used queries for faster execution, especially in EF Core.</li>



<li class="custp1"><strong>Optimize Database Schema</strong>: Ensure indexes, foreign keys, and database normalization support EF queries efficiently.</li>
</ol>



<br><br><br><br>



<div style="text-align: center;"><a href="https://api.whatsapp.com/send?text=Entity Framework Interview Questions and Answers - https://www.codeindotnet.com/entity-framework-interview-questions-answers/" rel="nofollow noopener" target="_blank" style="font-size: 18px; color: #fff; background-color: #03a941; border-radius: 5px; padding: 7px 10px;">
<span style="font-size: 22px;"><i class="fa fa-whatsapp"></i></span>
<span>Share to Whatsapp</span> </a>
</div>
<br><br>



<div id="download-questions" style="border: solid 1px lightblue; padding: 10px;">
<button class="shbtn" style="float: right; border-radius: 20px;" onclick="saveQuestionsAsPDF()">Download</button>
<div><span style="font-weight: bold; font-size: 20px; color: #7100e2;">Download all Questions as .PDF</span></div>
<div id="questions"><br><br><center><span style="color:#808080;"><i>loading&#8230;</i></span></center></div>
</div>



<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>



<style>
.shbtn {
    color: #fff;
    padding: 6px 12px;
    margin-top: 8px;
}
.shbtnlist {
    color: #fff;
    padding: 3px 9px;
}
.shdt {
    box-shadow: lightblue 0px 1px 2px;
}
pre {
    margin-bottom: 0;
}
tbody>tr>th {
    font-weight: bold;
}
.p-lp-15 {
    padding-left: 0.9375rem;
}
</style>

<script>
	function showHideBlock(val) {
		var btnx = document.getElementById("shbtn" + val);
		var divx = document.getElementById("shdiv" + val);

		if (divx.style.display === "none") {
			divx.style.display = "block";
			btnx.innerHTML = "&#9650; <u>Hide example</u>";
		} else {
			divx.style.display = "none";
			btnx.innerHTML = "&#9660; <u>Show example</u>";
		}
	}
</script>



<script>
window.onload = function (){
	var shbtnarr = document.getElementsByClassName("shbtn");
	var alreadySeen ={};
	console.log("shbtn count: " + shbtnarr.length);
	console.log("find duplicate - Start ---"); 
	for (element of shbtnarr) {
		if (alreadySeen[element.id]){
			console.log(element.id);
			alreadySeen[element.id] = false;
		}
		else {
			alreadySeen[element.id] = true;
		}
	}
	console.log("find duplicate - End ---"); 
	console.log()
	console.log("--- sh(alreadySeen) ids ---");
	console.log(alreadySeen);
	/* for (var key in alreadySeen)
	{
		console.log(key + " : " +  alreadySeen[key]);
	} */


	/*Sl.No for H3*/
	var h3arr = document.getElementsByClassName("hLBRed");
	var questions = document.getElementById("questions");
	questions.innerHTML = "<br><br><div><h2><center><b><u>Entity Framework Interview Questions</u></b></center></h2></div><br>";
	var count = 1;
	var searchResult = "";
	for (h3 of h3arr) {
		questions.innerHTML = questions.innerHTML + "<div>" + "<b>" + count + ")</b> " + h3.innerText.replace(/[^\w\s#?.,=<>()]/gi, '').replace('<','&lt;').replace('>','&gt;') + "</div>";
		h3.innerHTML = "<b>" + count + ") " + h3.innerHTML + "</b>";
		h3.id = "q" + count;
		searchResult += '<div class="filter-list-item"><a href="#' + h3.id + '">' + h3.innerText + '</a></div>'
		count++;
	}

	document.getElementById('myList').innerHTML = searchResult;
};


/* Print Questions */
function saveQuestionsAsPDF(divId, title) { 
	if (document.getElementById("questions").innerText.trim().length == 0) return;

	var doc = new jsPDF();
	doc.fromHTML('<html><head></head><body><div>https://www.codeindotnet.com/all-interview-questions-and-answers/</div>' + document.getElementById("questions").innerHTML + '<br><br><br><div><b>See Other Questions &amp; Answers:</b> https://www.codeindotnet.com/all-interview-questions-and-answers/</div></body></html>');
	doc.save('entity-framework-interview-questons.pdf');
}

</script>



<script type="text/javascript">
        document.getElementById("myInput").addEventListener("keyup",
    		function searchFilter() {
    			// Declare variables
    			var input, filter, div, divs, a, i;
    			input = document.getElementById('myInput').value.replace(/\s{2,}/g, ' ').trim().toUpperCase();
				arrFilters = input.split(' ');
    			div = document.getElementById('myList');
    			divs = div.getElementsByClassName('filter-list-item');
				
    			if (document.getElementById("myList").style.display == "none"){
    				document.getElementById("myList").style.display = "block";
    			}

				if(input.length == 0){
					for (i = 0; i < divs.length; i++) {
						divs[i].style.display = '';						
					}
				}
				else {
					// Loop through all list items, and hide those who don't match the search query
					for (i = 0; i < divs.length; i++) {
						a = divs[i].getElementsByTagName('a')[0];
						divs[i].style.display = 'none';
						for (j = 0; j < arrFilters.length; j++) {
							if ((arrFilters[j].length > 0) && (a.innerHTML.toUpperCase().indexOf(arrFilters[j]) > -1)) {
								divs[i].style.display = '';
								break;
							} 						
						}
						
					}
				}
    
		});
    </script>



<script>
function displayAllResult(){
	document.getElementById("myInput").value = ''
	div = document.getElementById('myList');
	divs = div.getElementsByClassName('filter-list-item');
	for (i = 0; i < divs.length; i++) {
		divs[i].style.display = '';						
	}
}
</script>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/entity-framework-interview-questions-answers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Top 80+ Web API Interview Questions &#038; Answers</title>
		<link>https://www.codeindotnet.com/web-api-interview-questions-answers/</link>
					<comments>https://www.codeindotnet.com/web-api-interview-questions-answers/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 31 Aug 2024 06:54:42 +0000</pubDate>
				<category><![CDATA[Interview Questions Answers]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=9118</guid>

					<description><![CDATA[Here are the top 80+ Web API interview questions and answers for beginners and professionals. Other Interview Questions &#8211; OOPs, C#, SQL Web API Interview Questions &#38; Answers Download all Questions as .PDF Search: Clear × What is Web API? A Web API is a framework that allows you to build HTTP services that can [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" src="/img/1/qa/web-api-interview-questions-answers-csharp-2.jpg" alt="Web API Interview Questions &amp; Answers"/></figure></div>


<br>



<p>Here are the top 80+ Web API interview questions and answers for beginners and professionals. </p>



<p class="has-text-align-right"><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"><strong>Other Interview Questions &#8211;</strong></mark> <a href="/oops-interview-questions-answers/" data-type="post" data-id="7894"><strong>OOPs</strong></a>, <strong><a href="/csharp-interview-questions-answers/" data-type="post" data-id="8095">C#</a></strong>, <strong><a href="/sql-interview-questions-answers/" data-type="post" data-id="7407">SQL</a></strong></p>



<br>



<h2 class="wp-block-heading h2Cust1"><strong>Web API Interview Questions &amp; Answers</strong></h2>



<p class="has-text-align-right"><strong><a href="#download-questions" data-type="internal" data-id="#download-questions">Download all Questions as .PDF</a></strong></p>



<div id="searchPopup">
	<div class="popup-header">			
		<span style="font-weight:bold;">Search: </span>
		<input type="text" id="myInput" autocomplete="off" placeholder=" type keyword(s) &amp; filter Questions..." onclick="document.getElementById('myList').style.display = 'block'; document.getElementById('btnpopclose').style.display = 'block';">
		<button onclick="displayAllResult();" style="padding: 5px 9px; border-radius: 10px; color:#fff;" >Clear</button>
		<button id="btnpopclose" class="popup-close" onclick="document.getElementById('myList').style.display = 'none'; document.getElementById('btnpopclose').style.display = 'none';">×</button>
	</div>
	<div id="myList"></div>		
</div>



<style>
.popup-close {
    font-size: 1.25rem;
    font-weight: 700;
    padding: .3125rem .625rem;
    border-radius: .3125rem;
    background-color: red;
    color: #fff;
    border: none;
    float: right;
    display: none;
    /*margin: -.3125rem;*/
}

#myInput{
width: calc(100% - 11.5625rem);
display:inline; 
border-radius: 10px; 
margin:0;
}


#searchPopup{
border: 1px solid #6a409759;
    padding: 10px;
    border-radius: 5px;
}

#myList{
line-height: 1.7; 
font-size: 16px; 
overflow-y: scroll; 
height: 250px; 
/*border-bottom: 3px lightgray solid;*/
display:none; 
margin-top: 15px;
}
</style>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Web API</strong>?</h3>



<p class="custp1 p-mb-0">A <strong>Web API</strong> is a framework that allows you to build HTTP services that can be consumed by a broad range of clients, including browsers, mobile devices, and other servers. It is a core component of the ASP.NET framework and is often used to create RESTful services. In other words, a Web API is an <strong>A</strong>pplication <strong>P</strong>rogramming <strong>I</strong>nterface for the Web.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the Key Concepts of Web API?</strong></h3>



<br>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>HTTP Services</strong>: Web APIs are built on top of HTTP, which is the foundation of web communication. You can use the standard HTTP methods like GET, POST, PUT, DELETE to perform CRUD (Create, Read, Update, Delete) operations.</li>



<li><strong>RESTful Services</strong>: Web API is often used to create RESTful services. REST (Representational State Transfer) is an architectural style that uses HTTP methods to operate on resources identified by URLs. Web APIs expose endpoints (URLs) that correspond to these resources.</li>



<li><strong>Serialization</strong>: Data is typically exchanged in formats like JSON or XML. ASP.NET Web API provides out-of-the-box support for these formats, making it easy to serialize and deserialize data.</li>



<li><strong>Routing</strong>: ASP.NET Web API uses routing to map HTTP requests to the appropriate controller actions. The routing mechanism can be customized to meet the specific needs of your application.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Why Use Web API?</strong></h3>



<br>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Interoperability</strong>: Web API allows different clients (such as web browsers, mobile applications, or even other servers) to interact with your application, regardless of the platform or language they are built in.</li>



<li><strong>Lightweight</strong>: Unlike WCF (Windows Communication Foundation), which is more complex and suitable for service-oriented applications, Web API is lightweight and designed specifically for HTTP services. This makes it faster and more suitable for web-based scenarios.</li>



<li><strong>Scalability</strong>: Since Web API is stateless, it is highly scalable. Each request is independent of others, which is a key factor in building high-performance, scalable applications.</li>



<li><strong>Testability</strong>: Web APIs are easy to test. You can use tools like Postman or write unit tests to <a href="/what-is-api-application-programming-interface/"><span class="cLink3">test the API endpoints</span></a> without needing a user interface.</li>



<li><strong>Integration with .NET Core</strong>: ASP.NET Core Web API, the cross-platform version, allows you to build and deploy Web APIs that run on various operating systems, including Windows, Linux, and macOS.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are some common use cases for Web API?</strong></h3>



<p class="custp1 p-mb-0"><strong><em>Common Use Cases for <strong><em>Web API</em></strong>:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Single Page Applications (SPAs)</strong>: Web APIs are often used as the backend services for SPAs built with frameworks like Angular, React, or Vue.js.</li>



<li><strong>Mobile Applications</strong>: Mobile apps commonly interact with a backend via Web APIs to fetch and update data.</li>



<li><strong>Microservices</strong>: In microservices architecture, each microservice might expose a Web API to communicate with other services or clients.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Explain the REST architectural style.</strong></h3>



<p class="custp1 p-mb-0">The <strong>REST (Representational State Transfer)</strong> architectural style is a set of principles for designing networked applications, particularly web services. REST is an architectural style, not a standard or protocol, and it is primarily used for designing APIs that can communicate over HTTP.</p>



<p class="custp1 p-mb-0"><strong><em>Key Principles of REST:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Resource-Based</strong>: Resources are identified by URIs (Uniform Resource Identifiers). For example, &#8216;https://api.example.com/users/123&#8217; might represent a user resource with the ID 123.</li>



<li><strong>Stateless Communication</strong>: RESTful services are stateless, meaning each HTTP request from a client to a server must contain all the information the server needs to fulfill that request. The server does not store any state information about the client session between requests or does not need to keep track of multiple client sessions.</li>



<li><strong>Standard HTTP Methods (verbs)</strong>: perform operations on resources &#8211; Get, Post, Put, Delete, Patch.</li>



<li><strong>Representation of Resources</strong>: Resources can have multiple representations, such as JSON, XML, or HTML, depending on what the client requests and what the server can provide. This is handled via content negotiation (using the <strong>Accept</strong> header in HTTP).</li>



<li><strong>Uniform Interface</strong>: REST promotes a uniform interface between clients and servers and this uniformity is achieved through consistent use of URIs, HTTP methods, headers, and status codes.</li>



<li><strong>Layered System</strong>: The client may not know whether it is communicating with the end server or an intermediary (such as a load balancer or a cache).</li>



<li><strong>Cacheable</strong>: Responses from RESTful services should explicitly indicate whether they are cacheable or not, using appropriate HTTP headers. Caching improves performance by reducing the number of client-server interactions.</li>



<li><strong>Client-Server Architecture</strong>: REST is based on a client-server architecture where the client and server have distinct responsibilities. The client handles the user interface, and the server manages and processes the resources. This separation of concerns allows for independent development and scaling of the client and server components.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the advantages of REST?</strong></h3>



<br>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Scalability</strong>: Because of its stateless nature, REST APIs can easily scale to handle a large number of clients.</li>



<li><strong>Performance</strong>: RESTful services can be made more performant by leveraging caching mechanisms.</li>



<li><strong>Flexibility</strong>: REST APIs can interact with different types of clients, including web browsers, mobile applications, and IoT devices, without needing client-specific adaptations.</li>



<li><strong>Interoperability</strong>: RESTful services can be consumed by different clients written in various programming languages, making it a highly interoperable architecture.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a RESTful service, and how does it relate to Web API?</strong></h3>



<p class="custp1 p-mb-0">A RESTful service is an application that follows the principles of Representational State Transfer (REST), which is an architectural style for designing networked applications. It uses standard HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources, which are typically represented by URLs.</p>



<p class="custp1 p-mb-0">In the context of Web API, a RESTful service is implemented using ASP.NET Web API to create HTTP-based services that are accessible via the web, allowing different clients (browsers, mobile apps, etc.) to interact with the server-side resources in a stateless manner.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between REST and SOAP in the context of Web APIs?</strong></h3>



<p class="custp1 p-mb-0"><strong>REST</strong> is ideal for simpler, stateless, and scalable web services with lightweight communication, commonly using JSON.</p>



<p class="custp1 p-mb-0"><strong>SOAP</strong> is better suited for enterprise-level services requiring strict standards, security, and ACID transactions, using XML.</p>



<br>
<div style="height:18.75rem; overflow-y:scroll; border: 1px solid #d3d3d3;">
<table style="margin: 0;">
    <thead>
        <tr>
            <th>REST</th>
            <th>SOAP</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>REST is an architectural style, not a protocol. It uses standard HTTP protocols (GET, POST, PUT, DELETE, etc.).</td>
            <td>SOAP is a protocol that operates over HTTP, SMTP, and other protocols.</td>
        </tr>
        <tr>
            <td>REST typically uses JSON or XML for data interchange, with JSON being more common due to its lightweight nature.</td>
            <td>SOAP uses XML exclusively for message formatting.</td>
        </tr>
        <tr>
            <td>REST is generally simpler and easier to implement, making it suitable for web-based applications.</td>
            <td>SOAP is more complex with strict standards, suited for enterprise-level applications.</td>
        </tr>
        <tr>
            <td>REST is stateless, meaning each request from a client to the server must contain all the information needed to understand and process the request.</td>
            <td>SOAP can be stateless or stateful, supporting operations like maintaining a session.</td>
        </tr>
        <tr>
            <td>REST is lightweight and faster because it typically uses JSON, which is less verbose than XML.</td>
            <td>SOAP is generally slower due to the overhead of XML and additional processing.</td>
        </tr>
        <tr>
            <td>REST relies on HTTPS for security, with authentication methods like OAuth.</td>
            <td>SOAP has built-in security features like WS-Security for message-level security.</td>
        </tr>
        <tr>
            <td>REST uses standard HTTP status codes for error handling (e.g., 404 for Not Found, 500 for Internal Server Error).</td>
            <td>SOAP has its own set of error handling standards through the use of &lt;fault&gt; elements in the XML response.</td>
        </tr>
        <tr>
            <td>REST does not require a strict contract; the API can evolve over time.</td>
            <td>SOAP requires a service contract defined by WSDL (Web Services Description Language).</td>
        </tr>
        <tr>
            <td>REST is more flexible and allows for multiple formats (JSON, XML, HTML, etc.) based on client needs.</td>
            <td>SOAP is rigid due to strict protocols and XML format.</td>
        </tr>
        <tr>
            <td>REST is commonly used for web services and public APIs where simplicity, scalability, and performance are key.</td>
            <td>SOAP is often used in enterprise environments where robust security, ACID compliance, and formal contracts are required.</td>
        </tr>
    </tbody>
</table>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are different standard HTTP methods?</strong></h3>



<p class="custp1 p-mb-0">In RESTful APIs, standard HTTP methods (also known as HTTP verbs) are used to perform operations or specific actions on resources. and they follow the CRUD (Create, Read, Update, Delete) pattern. </p>



<p class="custp1 p-mb-0">Here are the main HTTP methods:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>GET</strong>: Retrieve data.</li>



<li><strong>POST</strong>: Create a new resource.</li>



<li><strong>PUT</strong>: Update or create a resource.</li>



<li><strong>DELETE</strong>: Remove a resource.</li>



<li><strong>PATCH</strong>: Apply partial updates.</li>



<li><strong>OPTIONS</strong>: Discover available methods.</li>



<li><strong>HEAD</strong>: Retrieve headers without the body.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between [HttpGet], [HttpPost], [HttpPut], and [HttpDelete] attributes?</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th>Attribute</th>
            <th>HTTP Method</th>
            <th>Usage</th>
            <th>Purpose</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>[HttpGet]</td>
            <td>GET</td>
            <td>Read data</td>
            <td>Retrieves data from the server without modifying it. Typically used for fetching resources.<pre class="pchl" style="margin-top: 5px !important;"><code><span class="key">public</span> IActionResult GetItem(<span class="key">int</span> id) </code></pre>
        </tr>
        <tr>
            <td>[HttpPost]</td>
            <td>POST</td>
            <td>Create data</td>
            <td>Sends data to the server to create a new resource. Often used for submitting forms or posting data. <pre class="pchl" style="margin-top: 5px !important;"><code><span class="key">public</span> IActionResult CreateItem([<span class="custkey">FromBody</span>] Item item) </code></pre></td>
        </tr>
        <tr>
            <td>[HttpPut]</td>
            <td>PUT</td>
            <td>Update data</td>
            <td>Updates an existing resource on the server. Usually requires the entire resource to be sent for updating. <pre class="pchl" style="margin-top: 5px !important;"><code><span class="key">public</span> IActionResult UpdateItem(<span class="key">int</span> id, [<span class="custkey">FromBody</span>] Item item) </code></pre></td>
        </tr>
        <tr>
            <td>[HttpDelete]</td>
            <td>DELETE</td>
            <td>Delete data</td>
            <td>Removes a resource from the server. Used for deleting resources identified by a URI. <pre class="pchl" style="margin-top: 5px !important;"><code><span class="key">public</span> IActionResult DeleteItem(<span class="key">int</span> id) </code></pre></td>
        </tr>
    </tbody>
</table>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the differences between PUT and PATCH</strong>?</h3>



<br>
<table>
    <thead>
        <tr>
            <th>PUT</th>
            <th>PATCH</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Replaces the entire resource with the provided data.</td>
            <td>Updates only the specified fields in the resource.</td>
        </tr>
        <tr>
            <td>Request Body contains the full representation of the resource.</td>
            <td>Request Body contains a partial representation with only the changes.</td>
        </tr>
        <tr>
            <td>PUT is idempotent, meaning multiple identical requests result in the same outcome.</td>
            <td>PATCH is also idempotent, but only if the changes are the same each time.</td>
        </tr>
        <tr>
            <td>Use when you want to update all fields of a resource, even if only a few fields are changed.<br><br>example &#8211; Updating a user’s entire profile information.</td>
            <td>Use when you want to update only specific fields or parts of a resource.<br><br>example &#8211; Updating just the email address of a user.</td>
        </tr>
    </tbody>
</table>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is CRUD? What is the syntax for CRUD operations in Web API?</strong></h3>



<p class="custp1 p-mb-0"><strong>CRUD</strong> stands for <strong>Create, Read, Update, and Delete</strong>. These are the four basic operations that can be performed on data in a database or any persistent storage system.</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Create:</strong> Adding new data or records to a database (e.g., adding a new user).</li>



<li><strong>Read:</strong> Retrieving or reading data from the database (e.g., fetching user details).</li>



<li><strong>Update:</strong> Modifying existing data or records in the database (e.g., updating user information).</li>



<li><strong>Delete:</strong> Removing data or records from the database (e.g., deleting a user account).</li>
</ul>



<button class="shbtn" id="shbtn69261" onclick="showHideBlock(69261)">&#9660; <u>Show example</u></button>
<div id="shdiv69261" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Web API Syntax Example for CRUD operations:</b></div>
<pre class="pchl"><code><span class="com">// <b>Create</b> (POST)</span>
[<span class="custkey">HttpPost</span>]
<span class="key">public</span> IActionResult Create([FromBody] Product product)
{
    <span class="com">// Add new product to the database</span>
    <span class="key">return</span> CreatedAtAction(nameof(GetById), <span class="key">new</span> { id = product.Id }, product);
}

<span class="com">// <b>Read</b> (GET)</span>
[<span class="custkey">HttpGet</span>(<span class="str">"{id}"</span>)]  <span class="com">// ../Product/5</span>
<span class="key">public</span> IActionResult GetById(<span class="key">int</span> id)
{
    <span class="com">// Retrieve product by id from the database</span>
    <span class="key">var</span> product = _context.Products.Find(id);
    <span class="key">if</span> (product == <span class="key">null</span>)
    {
        <span class="key">return</span> NotFound();
    }
    <span class="key">return</span> Ok(product);
}

<span class="com">// <b>Update</b> (PUT)</span>
[<span class="custkey">HttpPut</span>(<span class="str">"{id}"</span>)]
<span class="key">public</span> IActionResult Update(<span class="key">int</span> id, [FromBody] Product product)
{
    <span class="key">if</span> (id != product.Id)
    {
        <span class="key">return</span> BadRequest();
    }
    
    <span class="com">// Update existing product in the database</span>
    _context.Entry(product).State = EntityState.Modified;
    _context.SaveChanges();
    
    <span class="key">return</span> NoContent();
}

<span class="com">// <b>Delete</b> (DELETE)</span>
[<span class="custkey">HttpDelete</span>(<span class="str">"{id}"</span>)]
<span class="key">public</span> IActionResult Delete(<span class="key">int</span> id)
{
    <span class="key">var</span> product = _context.Products.Find(id);
    <span class="key">if</span> (product == <span class="key">null</span>)
    {
        <span class="key">return</span> NotFound();
    }
    
    <span class="com">// Remove product from the database</span>
    _context.Products.Remove(product);
    _context.SaveChanges();
    
    <span class="key">return</span> NoContent();
} </code></pre>




<br><br>
<div style="padding-left: 0.3125rem;"><b>Other Web API Syntax Examples:</b></div>
<pre class="pchl"><code><span class="com">// ../Product/GetAllSales</span>
[<span class="custkey">HttpGet</span>(<span class="str">"GetAllSales"</span>)]
<span class="key">public</span> IActionResult GetAllSales()
{
    <span class="com">// ....</span>
}

<span class="com">// ../Product/Pairing/33</span>
[<span class="custkey">HttpGet</span>(<span class="str">"Pairing/{level3Id}"</span>)]
<span class="key">public</span> IActionResult GetPairings(<span class="key">int</span> level3Id)
{
    <span class="com">// ....</span>
}


<span class="com">/* <b>QueryString Example</b>*/</span>
<span class="com">// ../Product/2?version=111</span>
[<span class="custkey">HttpGet</span>(<span class="str">"ListFiles/{level3Id}"</span>)]
<span class="key">public</span> IActionResult ListFiles(<span class="key">int</span> level3Id, <span class="key">string</span> queryStringParam)
{
    <span class="com">// ....</span>
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What default Structure do you see once a new Web API project is created in .NET?</strong></h3>



<p class="custp1 p-mb-0">Once the project is created, you&#8217;ll see the following structure:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Controllers</strong>: This folder contains your API controllers, where each controller defines endpoints.</li>



<li><strong>Program.cs</strong>: The entry point of your application where the application is configured.</li>



<li><strong>appsettings.json</strong>: Configuration file for your application settings.</li>



<li><strong>Startup.cs</strong>: (For older .NET Core versions) Contains configuration and services setup.</li>



<li><strong>Properties/launchSettings.json</strong>: Contains settings for debugging and launching your application.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Controllers and Actions in Web API?</strong></h3>



<p class="custp1 p-mb-0"><strong>Controllers</strong> are classes that handle incoming HTTP requests. They group related actions together, usually focused on a specific resource (like &#8220;Products&#8221; or &#8220;Users&#8221;). </p>



<p class="custp1 p-mb-0"><strong>Actions</strong> are methods within controllers that process specific requests. Each action corresponds to an HTTP request type (like GET, POST, PUT, DELETE) and performs operations like retrieving data, creating new entries, or updating records.</p>



<button class="shbtn" id="shbtn17730" onclick="showHideBlock(17730)">&#9660; <u>Show example</u></button>
<div id="shdiv17730" style="display: none;">

<pre class="pchl"><code><span style="background:#f2f19d;">[ApiController]</span>
<span style="background:#f2f19d;">[Route(<span class="str">"api/[controller]"</span>)]</span>
<span class="key">public</span> <span class="key">class</span> MyController : ControllerBase
{
    <span class="com"> // Action Method</span>
    <span style="background:#f2f19d;">[HttpGet]</span>
    <span class="key">public</span> IActionResult Get()
    {
        <span class="key">return</span> Ok(<span class="key">new</span> { Message = <span class="str">"Hello, World!"</span> });
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Routing in Web API?</strong></h3>



<p class="custp1 p-mb-0"><strong>Routing</strong> in a Web API is the mechanism that maps incoming HTTP requests to specific action methods in a controller. It determines how the requests are processed and which actions should handle them based on the URL, HTTP method (GET, POST, PUT, DELETE, etc.), and other route data.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Types of routing in Web API</strong></h3>



<p class="custp1 p-mb-0">In a Web API, there are two main types of routing:</p>



<p class="custp1 p-mb-0"><strong>1) Attribute-Based Routing:</strong> Routes are defined directly on the controller and action methods using attributes like <span class="spanHT">[HttpGet]</span>, <span class="spanHT">[HttpPost]</span>, etc. Provides more control over the routes, allowing for customized and complex URL structures. </p>



<button class="shbtn" id="shbtn27620" onclick="showHideBlock(27620)">&#9660; <u>Show example</u></button>
<div id="shdiv27620" style="display: none;" class="shdt">

<br>
<div>The route <b>api/products/{id}</b> is defined directly on the <b>GetProduct</b> method.</div>


<pre class="pchl"><code>[Route(<span class="str">"api/products"</span>)]
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    <span style="background:#f2f19d;">[HttpGet(<span class="str">"{id}"</span>)]</span>
    <span class="key">public</span> IActionResult GetProduct(<span class="key">int</span> id) { ... }
} </code></pre>

</div>
<br>



<p class="custp1 p-mb-0"><strong>2) Conventional Routing:</strong> Routes are defined globally in a central place, typically in the <strong>Program.cs</strong> or <strong>Startup.cs</strong> file, using a pattern that applies to all controllers (<strong><em>for older versions of ASP.NET Core</em></strong>). Best for simpler applications where all controllers follow a consistent or standard URL structure.</p>



<button class="shbtn" id="shbtn47646" onclick="showHideBlock(47646)">&#9660; <u>Show example</u></button>
<div id="shdiv47646" style="display: none;">

<pre class="pchl"><code>app.UseEndpoints(endpoints =&gt
{
    endpoints.MapControllerRoute(
        name: <span class="str">"default"</span>,
        pattern: <span class="str" style="background:#f2f19d;">"api/{controller}/{action}/{id?}"</span>);
}); </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Route Prefix?</strong></h3>



<p class="custp1 p-mb-0"><strong>Route Prefix</strong> is a common route path applied to all routes within a controller, allowing you to avoid repeating the same base path for each action method. </p>



<p class="custp1 p-mb-0">You can apply a common prefix to multiple routes using the <span class="spanHT">[Route]</span> attribute at the controller level.</p>



<button class="shbtn" id="shbtn74042" onclick="showHideBlock(74042)">&#9660; <u>Show example</u></button>
<div id="shdiv74042" style="display: none;" class="shdt">

<pre class="pchl"><code><span style="background:#f2f19d;">[Route(<span class="str">"api/products"</span>)]</span>
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    [HttpGet]
    <span class="key">public</span> IActionResult GetAllProducts()
    { .... }

    [HttpGet(<span class="str">"{id}"</span>)]
    <span class="key">public</span> IActionResult GetProductById(<span class="key">int</span> id)
    { .... }
} </code></pre>

<ul class="ol1 ol1-mb-0">
<li class="custp1">The <strong>[Route(&#8220;api/products&#8221;)]</strong> attribute is the route prefix.</li>

<li>It automatically adds <strong>api/products</strong> to all routes in the <strong>ProductsController</strong>.</li>

<li>The final routes become <strong>api/products</strong> for <strong>GetAllProducts</strong> and <strong>api/products/{id}</strong> for <strong>GetProductById</strong>.</li>
</ul>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Route Constraint in Web API?</strong></h3>



<p class="custp1 p-mb-0"><strong>Route constraints</strong> are rules that restrict route parameters to specific types or patterns, like requiring an integer (<span class="spanHT">{id:int}</span>) or a specific format, ensuring valid data is passed to action methods.</p>



<p class="custp1 p-mb-0">You can specify parameters in routes and apply constraints to them.</p>



<pre class="pchl"><code>[HttpGet(<span class="str">"products/<span style="background:#f2f19d;">{categoryId:int}</span>/items/<span style="background:#f2f19d;">{itemId:int}</span>"</span>)]
<span class="key">public</span> IActionResult GetItemByCategory(<span class="key">int</span> categoryId, <span class="key">int</span> itemId)
{
    <span class="key">return</span> Ok($<span class="str">"Category ID: {categoryId}, Item ID: {itemId}"</span>);
} </code></pre>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use Route Naming in Web API, and why is it useful?</strong></h3>



<p class="custp1 p-mb-0">Route naming allows you to assign a name to a route, which you can use to generate URLs dynamically within your application. Route names are useful for generating links, so that you can include a link in an HTTP response. To specify the route name, set the&nbsp;<strong>Name</strong>&nbsp;property on the attribute.</p>



<button class="shbtn" id="shbtn15700" onclick="showHideBlock(15700)">&#9660; <u>Show example</u></button>
<div id="shdiv15700" style="display: none;" class="shdt">

<pre class="pchl"><code>[<span class="custkey">HttpGet</span>(<span class="str">"{id}"</span>, <span style="background:#f2f19d;">Name = <span class="str">"GetProductById"</span></span>)]
<span class="key">public</span> IActionResult GetProductById(<span class="key">int</span> id)
{
    <span class="key">return</span> Ok($<span class="str">"Product {id}"</span>);
}

[<span class="custkey">HttpPost</span>]
<span class="key">public</span> IActionResult CreateProduct([<span class="custkey">FromBody</span>] <span class="key">string</span> product)
{
    <span class="key">return</span> CreatedAtRoute(<span class="str">"<span style="background:#f2f19d;">GetProductById</span>"</span>, <span class="key">new</span> { id = 1 }, product);
} </code></pre>

<div style="padding-left: 0.3125rem;">
<ul class="ol1 ol1-mb-0">
<li class="custp1"><b>[HttpGet(&#8220;{id}&#8221;, Name = &#8220;GetProductById&#8221;)]:</b> The Name property assigns a name to the route.
</li>
<li><b>CreatedAtRoute(&#8220;GetProductById&#8221;, new { id = 1 }, product):</b> Uses the route name to generate a URL pointing to the <b>GetProductById</b> action, making it easier to reference routes consistently throughout the application.
</li>
</ul>
</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference Between Created, CreatedAtAction and CreatedAtRoute</strong></h3>



<p class="custp1 p-mb-0"><strong>Created</strong>, <strong>CreatedAtAction</strong>, and <strong>CreatedAtRoute</strong> are methods used to return a response indicating that a resource has been successfully created. They differ in how they specify the location (URI) of the newly created resource.</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Created:</strong> Returns a 201 Created status code with a Location header containing the URI of the created resource. Use when you already know the exact URI of the newly created resource.
<div>
<button class="shbtnlist" id="shbtn18085" onclick="showHideBlock(18085)">▼ <u>Show example</u></button>
<div id="shdiv18085" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> IActionResult CreateProduct([<span class="custkey">FromBody</span>] Product product)
{
    <span class="key">var</span> uri = $<span class="str" style="background:#f2f19d;">"api/products/{product.Id}"</span>;
    <span class="key">return</span> <span style="background:#f2f19d;">Created</span>(uri, product);
} </code></pre>
</div>
</div>
</li>



<li class="custp1"><strong>CreatedAtAction:</strong> Returns a 201 Created status code and automatically generates the Location header based on a specific action. Use when you want the framework to generate the URI for the newly created resource based on a specified action method in the current or another controller.
<div>
<button class="shbtnlist" id="shbtn56335" onclick="showHideBlock(56335)">▼ <u>Show example</u></button>
<div id="shdiv56335" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> IActionResult CreateProduct([<span class="custkey">FromBody</span>] Product product)
{
    <span class="key">return</span> <span style="background:#f2f19d;">CreatedAtAction</span>(nameof(<span style="background:#f2f19d;">GetProductById</span>), <span class="key">new</span> { id = product.Id }, product);
}

<span class="key">public</span> IActionResult <span style="background:#f2f19d;">GetProductById</span>(<span class="key">int</span> id)
{
    <span class="com">// Retrieve and return product by id</span>
} </code></pre>

</div>
</div>
</li>



<li class="custp1"><strong>CreatedAtRoute:</strong> Returns a 201 Created status code and automatically generates the Location header based on a named route. Use when you want the framework to generate the URI for the newly created resource based on a named route.
<div>
<button class="shbtnlist" id="shbtn16151" onclick="showHideBlock(16151)">▼ <u>Show example</u></button>
<div id="shdiv16151" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> IActionResult CreateProduct([<span class="custkey">FromBody</span>] Product product)
{
    <span class="key">return</span> <span style="background:#f2f19d;">CreatedAtRoute</span>(<span class="str" style="background:#f2f19d;">"GetProductByIdRoute"</span>, <span class="key">new</span> { id = product.Id }, product);
}

[<span class="custkey">HttpGet</span>(<span class="str">"{id}"</span>, <span style="background:#f2f19d;">Name = <span class="str">"GetProductByIdRoute"</span></span>)]
<span class="key">public</span> IActionResult GetProductById(<span class="key">int</span> id)
{
    <span class="com">// Retrieve and return product by id</span>
} </code></pre>

</div>
</div>
</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle URL parameters in Web API?</strong></h3>



<p class="custp1 p-mb-0"><strong>URL parameters</strong> (also known as <strong>route parameters</strong>) can be handled by defining them in the route template and binding them to method parameters in your controller. Here&#8217;s how you can handle URL parameters:</p>



<ol class="ol1 ol1-mb-0">

<li class="custp1">URL Parameters in Route Template:
<div>
<button class="shbtnlist" id="shbtn15942" onclick="showHideBlock(15942)">&#9660; <u>Show example</u></button>
<div id="shdiv15942" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1) Single URL Parameters in Route Template:</b></div>
<pre class="pchl"><code>[HttpGet(<span class="str">"<span style="background:#f2f19d;">{id}</span>"</span>)]
<span class="key">public</span> IActionResult GetProduct(<span style="background:#f2f19d;"><span class="key">int</span> id</span>)
{
} </code></pre>

<div style="padding-left: 0.3125rem;" class="custp1"><b>URL Request:</b> /api/products/5</div>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2) Multiple URL Parameters in Route Template:</b></div>
<pre class="pchl"><code>[HttpGet(<span class="str">"<span style="background:#f2f19d;">{category}/{id}</span>"</span>)]
<span class="key">public</span> IActionResult GetProductByCategory(<span style="background:#f2f19d;"><span class="key">string</span> category, <span class="key">int</span> id</span>)
{
} </code></pre>

<div style="padding-left: 0.3125rem;" class="custp1"><b>URL Request:</b> /api/products/electronics/5</div>

</div>
</div>
</li>


<li class="custp1">Optional URL Parameters:
<div>
<button class="shbtnlist" id="shbtn16778" onclick="showHideBlock(16778)">&#9660; <u>Show example</u></button>
<div id="shdiv16778" style="display: none;" class="shdt">

<pre class="pchl"><code>[HttpGet(<span class="str">"<span style="background:#f2f19d;">{id?}</span>"</span>)]
<span class="key">public</span> IActionResult GetProduct(<span style="background:#f2f19d;">int? id</span>)
{
	<span class="com">// assign default value if id is null.</span>
} </code></pre>

<div style="padding-left: 0.3125rem;" class="custp1"><b>URL Request:</b> 
<br><b>1)</b> with parameter: /api/products/5
<br><b>2)</b> without parameter: /api/products
</div>

</div>
</div>
</li>


<li class="custp1">Query String Parameters:
<div>
<button class="shbtnlist" id="shbtn71302" onclick="showHideBlock(71302)">&#9660; <u>Show example</u></button>
<div id="shdiv71302" style="display: none;" class="shdt">

<pre class="pchl"><code>[HttpGet(<span class="str">"search"</span>)]
<span class="key">public</span> IActionResult SearchProducts(<span style="background:#f2f19d;">[FromQuery]</span> <span class="key">string</span> name)
{
} </code></pre>


<div style="padding-left: 0.3125rem;" class="custp1"><b>URL Request:</b> /api/products/search?name=phone</div>

</div>
</div>
</li>

</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle multiple versions of a Web API?</strong></h3>



<p class="custp1 p-mb-0">Handling multiple versions of a Web API is essential when you need to support different versions of your API while maintaining backward compatibility for existing clients. </p>



<p class="custp1 p-mb-0"><strong><em>Common Versioning Strategies:</em></strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>URI Path Versioning:</strong> The version number is included in the URL path of the API endpoint.
<div>
<pre class="pchl" style="margin:0 !important;"><code>GET /api/v1/products
GET /api/v2/products </code></pre>
</div>
<em>Advantages:</em> Clear and easy to understand. Makes it straightforward to manage multiple versions.<br><em>Disadvantages:</em> Can lead to duplication of routes. Less flexible if versioning requirements become complex. 
</li>



<li class="custp1"><strong>Query String Versioning:</strong> The version number is passed as a query string parameter in the API request.
<div>
<pre class="pchl" style="margin:0 !important;"><code>GET /api/products?version=1
GET /api/products?version=2 </code></pre>
</div>
<em>Advantages:</em> Keeps the URI structure clean.<br><em>Disadvantages:</em> Can be less discoverable or intuitive for clients. May be overlooked in caching mechanisms.
</li>



<li class="custp1"><strong>Header Versioning:</strong> The version number is specified in the HTTP headers of the request.
<div>
<pre class="pchl" style="margin:0 !important;"><code>GET /api/products
Headers: API-Version: 1 </code></pre>
</div>
<em>Advantages:</em> Separates versioning information from the URI. Allows the URI to remain clean and consistent.<br><em>Disadvantages:</em> Not immediately visible in the URI. Clients need to be aware of the correct headers to use.
</li>



<li class="custp1"><strong>Namespace Versioning:</strong> Different versions of the API are separated by using different namespaces in the codebase.
<div>
<pre class="pchl" style="margin:0 !important;"><code>Version 1 Controller: Controllers.V1.ProductsController
Version 2 Controller: Controllers.V2.ProductsController </code></pre>
</div>
<em>Advantages:</em> Clean organization of code.<br><em>Disadvantages:</em> Can lead to duplicated code if not managed properly.
</li>



<li class="custp1"><strong>Accept Header Versioning (Media Type Versioning):</strong> The version is specified in the Accept header as part of the media type.
<div>
<pre class="pchl" style="margin:0 !important;"><code>GET /api/products
Headers: Accept: application/vnd.yourapi.v1+json </code></pre>
</div>
<em>Advantages:</em> Clean URI. Allows for content negotiation.<br><em>Disadvantages:</em> Complex for clients to understand and implement. Less intuitive.
</li>
</ol>



<button class="shbtn" id="shbtn48111" onclick="showHideBlock(48111)">&#9660; <u>Show example</u></button>
<div id="shdiv48111" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Implementing API Versioning:</b></div>

<br>
<div style="padding-left: 0.3125rem;"><b>1) Configure API Versioning in Program.cs or Startup.cs:</b></div>
<pre class="pchl"><code>services.AddApiVersioning(options =&gt
{
    options.DefaultApiVersion = <span class="key">new</span> ApiVersion(1, 0);
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.ReportApiVersions = true;
    options.ApiVersionReader = <span class="key">new</span> UrlSegmentApiVersionReader(); <span class="com">// or QueryStringApiVersionReader(), HeaderApiVersionReader()</span>
}); </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2) Define API Versions in Your Controllers:</b>
<br>
a) Using URI Path Versioning.
</div>
<pre class="pchl"><code>[ApiVersion(<span class="str">"1.0"</span>)]
[Route(<span class="str">"api/v{version:apiVersion}/products"</span>)]
[ApiController]
<span class="key">public</span> <span class="key">class</span> ProductsV1Controller : ControllerBase
{
    [HttpGet]
    <span class="key">public</span> IActionResult Get() =&gt Ok(<span class="str">"Version 1"</span>);
}

[ApiVersion(<span class="str">"2.0"</span>)]
[Route(<span class="str">"api/v{version:apiVersion}/products"</span>)]
[ApiController]
<span class="key">public</span> <span class="key">class</span> ProductsV2Controller : ControllerBase
{
    [HttpGet]
    <span class="key">public</span> IActionResult Get() =&gt Ok(<span class="str">"Version 2"</span>);
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">b) Using Header Versioning</div>
<pre class="pchl"><code>[ApiVersion(<span class="str">"1.0"</span>)]
[Route(<span class="str">"api/products"</span>)]
[ApiController]
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    [HttpGet]
    <span class="key">public</span> IActionResult GetV1() =&gt Ok(<span class="str">"Version 1"</span>);

    [HttpGet, MapToApiVersion(<span class="str">"2.0"</span>)]
    <span class="key">public</span> IActionResult GetV2() =&gt Ok(<span class="str">"Version 2"</span>);
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Explain the use of IHttpActionResult in returning HTTP responses.</strong></h3>



<p class="custp1 p-mb-0"><strong>IHttpActionResult</strong> is an interface that simplifies the process of creating HTTP responses. It provides a clean and standardized way to return responses from API actions. It provides built-in methods to generate common HTTP responses (e.g., <span class="spanHT">Ok</span>, <span class="spanHT">BadRequest</span>) and this reduces the need to manually create HttpResponseMessage objects.</p>



<p class="custp1 p-mb-0"><strong><em>Common &#8216;IHttpActionResult&#8217; Methods:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Ok()</strong>: Returns a 200 OK response.</li>



<li><strong>BadRequest()</strong>: Returns a 400 Bad Request response.</li>



<li><strong>NotFound()</strong>: Returns a 404 Not Found response.</li>



<li><strong>Created()</strong>: Returns a 201 Created response with a URI to the newly created resource.</li>



<li><strong>Unauthorized()</strong>: Returns a 401 Unauthorized response.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Middleware?</strong></h3>



<p class="custp1 p-mb-0">Middleware is a fundamental concept where various components are assembled into a pipeline to handle HTTP requests and responses. Each middleware component can perform operations before &amp; after the next component in the pipeline is invoked and can handle tasks like logging, authentication, and error handling, and can either pass control to the next component or short-circuit the pipeline by returning a response directly. Middleware components are executed in the order they are registered in the Startup.cs file (Configure method).</p>



<button class="shbtn" id="shbtn60471" onclick="showHideBlock(60471)">&#9660; <u>Show example</u></button>
<div id="shdiv60471" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        <span class="key">if</span> (env.IsDevelopment())
        {
            <span class="com">// ....</span>
        }

        app.UseHttpsRedirection(); <span class="com">// Redirect HTTP requests to HTTPS</span>
        app.UseRouting(); <span class="com">// Middleware to route requests</span>

        app.UseAuthentication(); <span class="com">// Middleware to handle authentication</span>
        app.UseAuthorization();  <span class="com">// Middleware to handle authorization</span>

        app.UseEndpoints(endpoints =&gt
        {
            endpoints.MapControllers(); <span class="com">// Middleware to map controllers</span>
        });
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How to Create Custom Middleware?</strong></h3>



<p class="custp1 p-mb-0">You can create custom middleware to handle specific tasks within the request pipeline. Creating custom middleware in ASP.NET Core Web API allows you to add custom processing logic to the HTTP request and response pipeline. Custom middleware can be used for tasks such as logging, request modification, response handling, or even custom authentication mechanisms. </p>



<p class="custp1 p-mb-0"><strong><em>Steps to Create Custom Middleware:</em></strong></p>



<ul class="ol1 ol-mb-0">

<li class="custp1"><strong>Create a Custom Middleware Class:</strong> The custom middleware class needs to have a constructor that takes a <span class="spanHT">RequestDelegate</span> parameter and an <span class="spanHT">Invoke</span> or <span class="spanHT">InvokeAsync</span> method that processes the HTTP context.</li>
<button class="shbtnlist" id="shbtn63975" onclick="showHideBlock(63975)">&#9660; <u>Show example</u></button>
<div id="shdiv63975" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> CustomMiddleware
{
    <span class="key">private</span> <span class="key">readonly</span> <span style="background:#f2f19d;">RequestDelegate</span> _next;

    <span class="key">public</span> CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    <span class="key">public</span> <span class="key">async</span> Task <span style="background:#f2f19d;">InvokeAsync</span>(HttpContext context)
    {
        <span class="com">// Pre-processing logic before passing to the next middleware</span>
        Console.WriteLine($<span class="str">"Request Path: {context.Request.Path}"</span>);

        <span class="com">// Call the next middleware in the pipeline</span>
        <span class="key">await</span> _next(context);

        <span class="com">// Post-processing logic after the next middleware has run</span>
        Console.WriteLine($<span class="str">"Response Status Code: {context.Response.StatusCode}"</span>);
    }
} </code></pre>

</div>


<li class="custp1"><strong>Register the Custom Middleware in the Request Pipeline:</strong> To use your custom middleware, you need to register it in the pipeline using the <span class="spanHT">UseMiddleware</span> extension method in the <span class="spanHT">Startup.cs</span> or <span class="spanHT">Program.cs</span> file.</li>
<button class="shbtnlist" id="shbtn52749" onclick="showHideBlock(52749)">&#9660; <u>Show example</u></button>
<div id="shdiv52749" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        <span class="key">if</span> (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        <span class="com">// Register the custom middleware</span>
        app.<span style="background:#f2f19d;">UseMiddleware&lt;CustomMiddleware&gt()</span>;

        <span class="com">// Other middleware registrations</span>
        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =&gt
        {
            endpoints.MapControllers();
        });
    }
} </code></pre>

</div>


</ul>



<p class="custp1 p-mb-0"><strong>(Optional) Middleware as an Extension Method:</strong> You can create an extension method to simplify the registration of your custom middleware, making it more reusable and easier to configure.</p>



<button class="shbtn" id="shbtn94642" onclick="showHideBlock(94642)">&#9660; <u>Show example</u></button>
<div id="shdiv94642" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">static</span> <span class="key">class</span> CustomMiddlewareExtensions
{
    <span class="key">public</span> <span class="key">static</span> <b>IApplicationBuilder</b> <span style="background:#f2f19d;">UseCustomMiddleware</span>(<span class="key">this</span> <b>IApplicationBuilder</b> builder)
    {
        <span class="key">return</span> builder.UseMiddleware&lt;<span style="background:#f2f19d;">CustomMiddleware</span>&gt();
    }
}

<span class="com">// Register using the extension method</span>
<span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        <span class="key">if</span> (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        <span class="com">// Register the custom middleware using the extension method</span>
        app.<span style="background:#f2f19d;">UseCustomMiddleware()</span>;

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =&gt
        {
            endpoints.MapControllers();
        });
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>In what order are middleware components executed?</strong></h3>



<p class="custp1 p-mb-0">Middleware components execute the request in the order they are registered in the <strong>Startup.cs</strong> file in the <strong>Configure</strong> method. It&#8217;s important to add middleware in the correct order; otherwise, the application might not work properly. This order is crucial for ensuring security, performance, and proper functionality. </p>



<button class="shbtn" id="shbtn19176" onclick="showHideBlock(19176)">&#9660; <u>Show example</u></button>
<div id="shdiv19176" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="com">// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.</span>
    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseExceptionHandler();
        app.UseHsts();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseRouting();
        app.UseCors();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseSession();
        app.UseMiddleware&lt;CustomMiddleware&gt();
        app.UseEndpoints(endpoints =&gt
        {
            endpoints.MapControllers();
        });

    }
} </code></pre>

</div>



<p class="custp1 p-mb-0">The following diagram shows the complete request processing pipeline.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" src="/img/1/qa/ans/middleware-components-execution-order.jpg" alt="middleware components execution order"/></figure></div>


<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Data Annotation?</strong></h3>



<p class="custp1 p-mb-0">Data Annotations are a set of attributes that you can apply to model properties or classes to enforce validation rules, specify formatting, and control how data is displayed. It ensures that the data received by API is correct and follows the rules. </p>



<p class="custp1 p-mb-0">Data Annotations are commonly used to <strong>validate</strong> user input like &#8216;required field&#8217; validation and to specify <strong>metadata</strong> about a model such as display names, descriptions, or format strings. It allows you to apply validation and metadata directly in the model class.</p>



<p class="custp1 p-mb-0"><strong>Common Data Annotation Attributes:</strong></p>



<div style="height:15.625rem; overflow-y:scroll; border: 1px solid #d3d3d3;">
<table style="margin: 0;">
    <thead>
        <tr>
            <th>Attribute</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>[Required]</td>
            <td>Ensures that the property must have a value.</td>
        </tr>
        <tr>
            <td>[Key]</td>
            <td>Indicates that the property is the primary key of the model.</td>
        </tr>
        <tr>
            <td>[DisplayName]</td>
            <td>Specifies a friendly name for the property to use in UI or error messages.</td>
        </tr>
        <tr>
            <td>[MaxLength]</td>
            <td>Specifies the maximum length of an array or string property.</td>
        </tr>
        <tr>
            <td>[MinLength]</td>
            <td>Specifies the minimum length of an array or string property.</td>
        </tr>
        <tr>
            <td>[StringLength]</td>
            <td>Sets the maximum (and optionally minimum) length of a string.</td>
        </tr>
        <tr>
            <td>[Range]</td>
            <td>Ensures that a numeric value falls within a specified range.</td>
        </tr>
        <tr>
            <td>[RegularExpression]</td>
            <td>Validates the string against a specified regular expression pattern.</td>
        </tr>
        <tr>
            <td>[EmailAddress]</td>
            <td>Validates that the string is in a valid email address format.</td>
        </tr>
        <tr>
            <td>[Phone]</td>
            <td>Ensures that the string is in a valid phone number format.</td>
        </tr>
        <tr>
            <td>[Url]</td>
            <td>Validates that the string is in a valid URL format.</td>
        </tr>
        <tr>
            <td>[Compare]</td>
            <td>Ensures that two properties have matching values.</td>
        </tr>
        <tr>
            <td>[CreditCard]</td>
            <td>Validates that the string is in a valid credit card format.</td>
        </tr>
        <tr>
            <td>[DataType]</td>
            <td>Specifies the data type (e.g., Date, Time, Currency) for better formatting.</td>
        </tr>
        <tr>
            <td>[DisplayFormat]</td>
            <td>Specifies the format for displaying the data, like dates or currency.</td>
        </tr>
        <tr>
            <td>[Timestamp]</td>
            <td>Marks a property as a database timestamp for concurrency control.</td>
        </tr>
        <tr>
            <td>[ScaffoldColumn]</td>
            <td>Hides the property from scaffolding processes like generating forms.</td>
        </tr>
        <tr>
            <td>[EnumDataType]</td>
            <td>Ensures that the property matches a specified enum type.</td>
        </tr>
        <tr>
            <td>[BindRequired]</td>
            <td>Ensures that the property must be present in the incoming data during binding.</td>
        </tr>
        <tr>
            <td>[BindNever]</td>
            <td>Prevents a property from being included in model binding.</td>
        </tr>
    </tbody>
</table>
</div>



<button class="shbtn" id="shbtn24883" onclick="showHideBlock(24883)">&#9660; <u>Show example</u></button>
<div id="shdiv24883" style="display: none;">
<pre class="pchl"><code><span class="key">using</span> System.ComponentModel.DataAnnotations;

<span class="key">public</span> <span class="key">class</span> Product
{
	[<span class="custkey">Required</span>(ErrorMessage = <span class="str">"Product ID is required"</span>)]
	[<span class="custkey">Display</span>(Name = <span class="str">"Product ID"</span>)]
	[<span class="custkey">Key</span>]
	<span class="key">public</span> <span class="key">int</span> Id { get; set; }

	[<span class="custkey">StringLength</span>(100, ErrorMessage = <span class="str">"Product name cannot exceed 100 characters"</span>)]
	<span class="key">public</span> <span class="key">string</span> Name { get; set; }

	[<span class="custkey">Range</span>(0.01, 10000, ErrorMessage = <span class="str">"Price must be between 0.01 and 10,000"</span>)]
	<span class="key">public</span> <span class="key">decimal</span> Price { get; set; }

	[<span class="custkey">EmailAddress</span>(ErrorMessage = <span class="str">"Invalid email address format"</span>)]
	<span class="key">public</span> <span class="key">string</span> SupplierEmail { get; set; }

	[<span class="custkey">MinLength</span>(3, ErrorMessage = <span class="str">"Product Code must be at least 3 characters long"</span>)]
	<span class="key">public</span> <span class="key">string</span> ProductCode { get; set; }

	[<span class="custkey">MaxLength</span>(100, ErrorMessage = <span class="str">"Title cannot exceed 100 characters"</span>)]
	<span class="key">public</span> <span class="key">string</span> Title { get; set; }

	[<span class="custkey">Phone</span>(ErrorMessage = <span class="str">"Please enter a valid phone number"</span>)]
	<span class="key">public</span> <span class="key">string</span> PhoneNumber { get; set; }

	[<span class="custkey">RegularExpression</span>(@<span class="str">"^[a-zA-Z]+$"</span>, ErrorMessage = <span class="str">"Only letters are allowed"</span>)]
	<span class="key">public</span> <span class="key">string</span> SupplierName { get; set; }

	[<span class="custkey">Url</span>(ErrorMessage = <span class="str">"Please enter a valid URL"</span>)]
	<span class="key">public</span> <span class="key">string</span> Website { get; set; }

} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are HTTP response methods?</strong></h3>



<p class="custp1 p-mb-0">HTTP response methods are built-in methods used to generate and return specific HTTP status codes and messages in response to client requests. You can use various HTTP response methods to indicate the outcome of an API request. Each method corresponds to a specific HTTP status code and is used to communicate different types of responses to the client.</p>



<p class="custp1 p-mb-0"><strong>Common HTTP Response Methods:</strong></p>



<div style="height:18.75rem; overflow-y:scroll; border: 1px solid #d3d3d3;">
<table style="margin: 0;">
    <thead>
        <tr>
            <th>Method</th>
            <th>Description</th>
            <th>HTTP Status Code &amp; Messages</th>
            <th>Typical Use Case</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Ok()</td>
            <td>Returns a successful response with a 200 OK status code. Includes data if needed.</td>
            <td>200 OK</td>
            <td>Use when a request is successful and you want to return data.</td>
        </tr>
        <tr>
            <td>Created()</td>
            <td>Indicates successful resource creation with a 201 Created status code. Includes the URI of the newly created resource.</td>
            <td>201 Created</td>
            <td>Use when a new resource is created and you want to provide its location.</td>
        </tr>
        <tr>
            <td>NoContent()</td>
            <td>Indicates that the request was successful but there is no content to return.</td>
            <td>204 No Content</td>
            <td>Use when the request is successful, but there is no data to return.</td>
        </tr>
        <tr>
            <td>BadRequest()</td>
            <td>Indicates that the request could not be processed due to client error (e.g., invalid input).</td>
            <td>400 Bad Request</td>
            <td>Use when the request is malformed or invalid.</td>
        </tr>
        <tr>
            <td>Unauthorized()</td>
            <td>Indicates that the request lacks valid authentication credentials.</td>
            <td>401 Unauthorized</td>
            <td>Use when authentication is required and the user is not authenticated.</td>
        </tr>
        <tr>
            <td>Forbidden()</td>
            <td>Indicates that the server understands the request but refuses to authorize it.</td>
            <td>403 Forbidden</td>
            <td>Use when the user does not have permission to access the resource.</td>
        </tr>
        <tr>
            <td>NotFound()</td>
            <td>Indicates that the requested resource could not be found.</td>
            <td>404 Not Found</td>
            <td>Use when the resource is not found.</td>
        </tr>
        <tr>
            <td>Conflict()</td>
            <td>Indicates that the request could not be completed due to a conflict with the current state of the resource.</td>
            <td>409 Conflict</td>
            <td>Use when there is a conflict with the current state of the resource.</td>
        </tr>
        <tr>
            <td>InternalServerError()</td>
            <td>Indicates that the server encountered an error while processing the request.</td>
            <td>500 Internal Server Error</td>
            <td>Use when an unexpected server error occurs.</td>
        </tr>
        <tr>
            <td>NotImplemented()</td>
            <td>Indicates that the server does not support the functionality required to fulfill the request.</td>
            <td>501 Not Implemented</td>
            <td>Use when the requested functionality is not supported by the server.</td>
        </tr>
        <tr>
            <td>ServiceUnavailable()</td>
            <td>Indicates that the server is currently unable to handle the request due to temporary overload or maintenance.</td>
            <td>503 Service Unavailable</td>
            <td>Use when the service is temporarily unavailable.</td>
        </tr>
    </tbody>
</table>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Filters?</strong></h3>



<p class="custp1 p-mb-0">A filter is a component that allows you to run custom logic(code) before or after an action method is executed, helping you handle tasks like authentication, authorization, logging, validation and exception handling across your API. It allows injecting reusable logic into the request processing pipeline.</p>



<p class="custp1 p-mb-0"><strong>Types of Filters:</strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Authorization Filters:</strong> Implements&nbsp;<span class="spanHT">IAuthorizationFilter</span>.</li>



<li><strong>Resource Filter:</strong> Implements IResourceFilter.</li>



<li><strong>Action Filters:</strong> Implements <span class="spanHT">IActionFilter</span>.</li>



<li><strong>Exception Filters:</strong> Implements <span class="spanHT">IExceptionFilter</span>.</li>



<li><strong>Result Filters:</strong> Implements <span class="spanHT">IResultFilter</span>.</li>
</ol>



<p class="custp1 p-mb-0">You can apply a filter globally, at the controller level, or at the action method level.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Authorization Filter?</strong></h3>



<p class="custp1 p-mb-0">An <strong>Authorization Filter</strong> is a filter that checks whether a user or client is authorized to execute a specific action or access a resource before the action method is executed, ensuring that only users with the proper credentials, roles, or permissions can proceed with the request. If the user is not authorized, the filter can block the request and return an appropriate response, such as a &#8216;401 Unauthorized&#8217; or &#8216;403 Forbidden&#8217; status code. The <strong>[Authorize]</strong> attribute is a built-in authorization filter.</p>



<p class="custp1 p-mb-0">You can create a custom authorization filter by implementing the <span class="spanHT">IAuthorizationFilter</span> interface and it has one method that you can override:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1">OnAuthorization(AuthorizationFilterContext) &#8211; Called early in the filter pipeline to confirm the request is authorized.</li>
</ul>



<button class="shbtn" id="shbtn84780" onclick="showHideBlock(84780)">&#9660; <u>Show example</u></button>
<div id="shdiv84780" style="display: none;">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Create a Custom Authorization Filter</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> CustomAuthorizationFilter : <span style="background:#f2f19d;">IAuthorizationFilter</span>
{
    <span class="key">public</span> <span class="key">void</span> OnAuthorization(AuthorizationFilterContext context)
    {
        <span class="key">var</span> user = context.HttpContext.User;

        <span class="key">if</span> (!user.Identity.IsAuthenticated)
        {
            <span class="com">// If the user is not authenticated, return 401 Unauthorized</span>
            context.Result = <span class="key">new</span> UnauthorizedResult();
        }
        <span class="key">else</span> <span class="key">if</span> (!user.IsInRole(<span class="str">"Admin"</span>))
        {
            <span class="com">// If the user is authenticated but not in the Admin role, return 403 Forbidden</span>
            context.Result = <span class="key">new</span> ForbidResult();
        }
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Apply the Authorization Filter</b>
<br>Authorization filters can be applied globally, at the controller level, or at the action method level.
<br><br><b>a.</b> At Global-Level:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
{
    services.AddControllers(options =&gt
    {
        options.<span style="background:#f2f19d;">Filters.Add(<span class="key">new</span> CustomAuthorizationFilter()</span>);
    });
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>b.</b> At Controller-Level:</div>
<pre class="pchl"><code><span style="background:#f2f19d;">[Authorize]</span>
[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    <span class="com">// Actions go here...</span>
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>c.</b> At Action-Level:</div>
<pre class="pchl"><code>[HttpGet(<span class="str">"{id}"</span>)]
<span style="background:#f2f19d;">[Authorize(Roles = <span class="str">"Admin"</span>)]</span>
<span class="key">public</span> IActionResult GetProduct(<span class="key">int</span> id)
{
    <span class="com">// Action logic...</span>
    <span class="key">return</span> Ok(<span class="key">new</span> { ProductId = id, Name = <span class="str">"Sample Product"</span> });
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Resource Filter?</strong></h3>



<p class="custp1 p-mb-0">A <strong>Resource Filter</strong> is a filter that runs before and after the execution of the rest of the request pipeline. Resource filters are executed after authorization filters but before model binding (Action Filters, Exception Filters, and Result Filters), making them ideal for tasks like caching, enforcing model validation, or short-circuiting the request pipeline. </p>



<p class="custp1 p-mb-0">You can create a custom resource filter by implementing the <span class="spanHT">IResourceFilter</span>&nbsp;interface and for async type <span class="spanHT">IAsyncResourceFilter</span> interface. It has the following methods that you can override:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>OnResourceExecuted(ResourceExecutedContext) &#8211; Called after execution of the remainder of the pipeline.</li>



<li>OnResourceExecuting(ResourceExecutingContext) &#8211; Called before execution of the remainder of the pipeline.</li>



<li>OnResourceExecutionAsync(ResourceExecutingContext, ResourceExecutionDelegate) &#8211; Called asynchronously before the rest of the pipeline.</li>
</ul>



<button class="shbtn" id="shbtn23518" onclick="showHideBlock(23518)">&#9660; <u>Show example</u></button>
<div id="shdiv23518" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;">Basic example of a custom resource filter that <b>checks for a cached response</b> and returns it if available:
<br><br><b>1. Create Resource Filter</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> CacheResourceFilter : <span style="background:#f2f19d;">IResourceFilter</span>
{
    <span class="key">private</span> <span class="key">readonly</span> IMemoryCache _cache;

    <span class="key">public</span> CacheResourceFilter(IMemoryCache cache)
    {
        _cache = cache;
    }

    <span class="key">public</span> <span class="key">void</span> OnResourceExecuting(ResourceExecutingContext context)
    {
        <span class="com">// Check if the response is already cached</span>
        <span class="key">if</span> (_cache.TryGetValue(context.HttpContext.Request.Path, <span class="key">out</span> <span class="key">var</span> cachedResponse))
        {
            context.Result = (IActionResult)cachedResponse; <span class="com">// Return the cached response</span>
        }
    }

    <span class="key">public</span> <span class="key">void</span> OnResourceExecuted(ResourceExecutedContext context)
    {
        <span class="com">// Cache the response if it wasn't already cached</span>
        <span class="key">if</span> (context.Result != <span class="key">null</span> && !_cache.TryGetValue(context.HttpContext.Request.Path, <span class="key">out</span> _))
        {
            _cache.Set(context.HttpContext.Request.Path, context.Result);
        }
    }
} </code></pre>



<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Apply Resource Filter</b>
<br>You can register the filter globally or apply it to all controllers and actions.
<br><br><b>a)</b> At Global-Level:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
{
    services.AddControllers(options =&gt
    {
        options.<span style="background:#f2f19d;">Filters.Add&lt;CacheResourceFilter&gt()</span>;
    });
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>b)</b> Controller or Action Level</div>
<pre class="pchl"><code><span style="background:#f2f19d;">[ServiceFilter(<span class="key">typeof</span>(CacheResourceFilter))]</span>
[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    [HttpGet(<span class="str">"{id}"</span>)]
    <span class="key">public</span> IActionResult GetProduct(<span class="key">int</span> id)
    {
        <span class="com">// Action logic...</span>
        <span class="key">return</span> Ok(<span class="key">new</span> { ProductId = id, Name = <span class="str">"Sample Product"</span> });
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Action Filter</strong>?</h3>



<p class="custp1 p-mb-0">An <strong>Action Filter</strong> is a filter that allows you to execute custom logic before and after an action method is executed. It&#8217;s useful for handling cross-cutting concerns like logging, validation, or modifying the result returned by an action.</p>



<p class="custp1 p-mb-0">You can create a custom action filter by deriving from the&nbsp;<span class="spanHT">ActionFilterAttribute</span>&nbsp;class and it has the following methods that you can override:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1">OnActionExecuted(ActionExecutedContext) &#8211; Called after the action method executes.</li>



<li>OnActionExecuting(ActionExecutingContext) &#8211; Called before the action method executes.</li>



<li>OnResultExecuted(ResultExecutedContext) &#8211; Called after the action result executes.</li>



<li>OnResultExecuting(ResultExecutingContext) &#8211; Called before the action result executes.</li>
</ul>



<button class="shbtn" id="shbtn1034" onclick="showHideBlock(1034)">&#9660; <u>Show example</u></button>
<div id="shdiv1034" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Create Action Filter</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span style="background:#f2f19d;">LogActionFilter</span> : <span style="background:#f2f19d;">ActionFilterAttribute</span>
{
	<span class="key">public</span> <span class="key">override</span> <span class="key">void</span> OnActionExecuting(ActionExecutingContext filterContext)
	{
	   Log(<span class="str">"OnActionExecuting"</span>, filterContext.RouteData);       
	}

	<span class="key">public</span> <span class="key">override</span> <span class="key">void</span> OnActionExecuted(ActionExecutedContext filterContext)
	{
	   Log(<span class="str">"OnActionExecuted"</span>, filterContext.RouteData);       
	}

	<span class="key">public</span> <span class="key">override</span> <span class="key">void</span> OnResultExecuting(ResultExecutingContext filterContext)
	{
	   Log(<span class="str">"OnResultExecuting"</span>, filterContext.RouteData);       
	}

	<span class="key">public</span> <span class="key">override</span> <span class="key">void</span> OnResultExecuted(ResultExecutedContext filterContext)
	{
	   Log(<span class="str">"OnResultExecuted"</span>, filterContext.RouteData);       
	}


	<span class="key">private</span> <span class="key">void</span> Log(<span class="key">string</span> methodName, RouteData routeData)
	{
	   <span class="key">var</span> controllerName = routeData.Values[<span class="str">"controller"</span>];
	   <span class="key">var</span> actionName = routeData.Values[<span class="str">"action"</span>];
	   <span class="key">var</span> message = String.Format(<span class="str">"{0} controller:{1} action:{2}"</span>, methodName, controllerName, actionName);
	   <span class="com">// Debug.WriteLine(message, "Action Filter Log");</span>
	}
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Apply the Action Filter</b>
<br>Apply a Action Filter globally or at the controller level, or at the action method level.</div>
<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span style="background:#f2f19d;">[LogActionFilter]</span> <span class="com">// Applied at the controller level</span>
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    [<span class="custkey">HttpGet</span>]
    <span class="key">public</span> IActionResult GetProducts()
    {
        <span class="com">// Action method logic</span>
        <span class="key">return</span> Ok(<span class="key">new</span> List&lt;<span class="key">string</span>&gt { <span class="str">"Product1"</span>, <span class="str">"Product2"</span> });
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Exception Filter?</strong></h3>



<p class="custp1 p-mb-0">An <strong>Exception Filter</strong> is a filter that handles exceptions thrown during the execution of an action method. It allows you to catch unhandled exceptions, log them, and return a custom error response to the client with a specific HTTP status code &amp; a custom error message. Exception filters are useful for centralizing error-handling logic across your application. </p>



<p class="custp1 p-mb-0">You can create a custom exception filter by implementing the <span class="spanHT">IExceptionFilter</span> interface or by deriving from the <span class="spanHT">ExceptionFilterAttribute</span> class and it has the following methods that you can override:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1">OnException(ExceptionContext)</li>



<li>OnExceptionAsync(ExceptionContext)</li>
</ul>



<button class="shbtn" id="shbtn91028" onclick="showHideBlock(91028)">&#9660; <u>Show example</u></button>
<div id="shdiv91028" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Create Custom Exception Filter</b></div>

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> CustomExceptionFilter : <span style="background:#f2f19d;">ExceptionFilterAttribute</span>
{
    <span class="key">public</span> <span class="key">override</span> <span class="key">void</span> OnException(ExceptionContext context)
    {
        <span class="com">// Log the exception (you can use any logging framework)</span>
        Console.WriteLine($<span class="str">"Exception caught: {context.Exception.Message}"</span>);

        <span class="com">// Customize the response</span>
        context.Result = <span class="key">new</span> ObjectResult(<span class="key">new</span>
        {
            Error = <span class="str">"An unexpected error occurred. Please try again later."</span>,
            Details = context.Exception.Message <span class="com">// Optional: Include details for debugging</span>
        })
        {
            StatusCode = StatusCodes.Status500InternalServerError
        };

        <span class="com">// Indicate that the exception has been handled</span>
        context.ExceptionHandled = true;
    }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Applying the Exception Filter</b>
<br>Exception filters can be applied globally, at the controller level, or at the action method level, giving you flexibility in where and how you handle exceptions.
<br><br><b>a.</b> At Global-Level:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
{
    services.AddControllers(options =&gt
    {
        options.<span style="background:#f2f19d;">Filters.Add(<span class="key">new</span> CustomExceptionFilter()</span>);
    });
} </code></pre>



<br><br>
<div style="padding-left: 0.3125rem;">You can use the <b>[TypeFilter]</b> or <b>[ServiceFilter]</b> attributes.
<br><b>b.</b> At Controller-Level:</div>
<pre class="pchl"><code><span style="background:#f2f19d;">[ServiceFilter(<span class="key">typeof</span>(CustomExceptionFilter))]</span>
[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    <span class="com">// Actions go here...</span>
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>c.</b> At Action-Level:</div>
<pre class="pchl"><code>[<span class="custkey">HttpGet</span>(<span class="str">"{id}"</span>)]
<span style="background:#f2f19d;">[TypeFilter(<span class="key">typeof</span>(CustomExceptionFilter))]</span>
<span class="key">public</span> IActionResult GetProduct(<span class="key">int</span> id)
{
    <span class="com">// Action logic...</span>
} </code></pre>


</div>
<br><br>



<p class="p-mb-0"><span style="border: 1px solid lightblue; padding: 7px 10px; border-radius: 10px;"><em><mark style="background-color:rgba(0, 0, 0, 0);color:#00008b" class="has-inline-color"><strong>read full post:</strong></mark></em> <a href="/create-custom-exception-filter-attribute-handler-class/" target="_blank" rel="noreferrer noopener"><span class="cLink3">How to Create Custom Exception Filter in .Net Core C#?</span></a></span></p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Result Filter?</strong></h3>



<p class="custp1 p-mb-0">A <strong>Result Filter</strong> is a filter that runs before and after the execution of an action result, which is the final step in processing a request. Result filters allow you to modify the action result or response before it is sent to the client, providing an opportunity to change or add the content, headers, status codes, or perform any other post-processing tasks. </p>



<p class="custp1 p-mb-0">You can create a custom result filter by implementing the <span class="spanHT">IResultFilter</span> interface or by deriving from the <span class="spanHT">ResultFilterAttribute</span> class and it has the following methods that you can override:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1">OnResultExecuted(ResultExecutedContext) &#8211; Called after the action result executes.</li>



<li>OnResultExecuting(ResultExecutingContext) &#8211; Called before the action result executes.</li>



<li>OnResultExecutionAsync(ResultExecutingContext, ResultExecutionDelegate) &#8211; Called asynchronously before the action result.</li>
</ul>



<button class="shbtn" id="shbtn22864" onclick="showHideBlock(22864)">&#9660; <u>Show example</u></button>
<div id="shdiv22864" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Create a Custom Result Filter</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> CustomResultFilter : <span style="background:#f2f19d;">ResultFilterAttribute</span>
{
    <span class="key">public</span> <span class="key">override</span> <span class="key">void</span> OnResultExecuting(ResultExecutingContext context)
    {
        <span class="com">// Code that runs before the result is executed</span>
        Console.WriteLine(<span class="str">"Before result execution: "</span> + context.Result.ToString());
    }

    <span class="key">public</span> <span class="key">override</span> <span class="key">void</span> OnResultExecuted(ResultExecutedContext context)
    {
        <span class="com">// Code that runs after the result has been executed</span>
        Console.WriteLine(<span class="str">"After result execution"</span>);
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Applying the Result Filter</b>
<br>Result filters can be applied globally or at the controller level or at the action method level.
<br><br><b>a.</b> At Global-Level:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
{
    services.AddControllers(options =&gt
    {
        options.<span style="background:#f2f19d;">Filters.Add(<span class="key">new</span> CustomResultFilter()</span>);
    });
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;">You can use the <b>[TypeFilter]</b> or <b>[ServiceFilter]</b> attributes.
<br><b>b.</b> At Controller-Level:</div>
<pre class="pchl"><code><span style="background:#f2f19d;">[ServiceFilter(<span class="key">typeof</span>(CustomResultFilter))]</span>
[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    <span class="com">// Actions go here...</span>
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>c.</b> At Action-Level:</div>
<pre class="pchl"><code>[<span class="custkey">HttpGet</span>(<span class="str">"{id}"</span>)]
<span style="background:#f2f19d;">[TypeFilter(<span class="key">typeof</span>(CustomResultFilter))]</span>
<span class="key">public</span> IActionResult GetProduct(<span class="key">int</span> id)
{
    <span class="com">// Action logic...</span>
    <span class="key">return</span> Ok(<span class="key">new</span> { ProductId = id, Name = <span class="str">"Sample Product"</span> });
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>In which order are filters executed in the request processing pipeline?</strong></h3>



<p class="custp1 p-mb-0">Filters work by providing hooks into the request processing pipeline, allowing you to execute custom logic at various stages of the request and response.</p>



<p class="custp1 p-mb-0"><strong>Filters are executed in a specific order:</strong> <span class="spanHT">Authorization Filters</span> → <span class="spanHT">Resource Filters</span> → <span class="spanHT">Action Filters</span> → <span class="spanHT">Exception Filters</span> → <span class="spanHT">Result Filters</span></p>



<p class="custp1 p-mb-0">The order of execution ensures that authorization happens first, followed by action execution, and finally, any result processing or exception handling. The following diagram shows how filter types interact in the filter pipeline:</p>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/qa/ans/filters-execution-order.jpg" alt="filters 0execution order of web api"/></figure>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the different ways to apply or implement filters in .NET Core Web API?</strong></h3>



<p class="custp1 p-mb-0">Multiple ways to apply filters, they are:</p>



<ul class="ol1 ol1-mb-0">

<li class="custp1"><strong>Global-Level:</strong> Filters can be registered globally in the <strong>Startup.cs</strong> file, applying them to all controllers and actions in the application.
<div>
<button class="shbtn" id="shbtn17098" onclick="showHideBlock(17098)">&#9660; <u>Show example</u></button>
<div id="shdiv17098" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>In &#39;Startup.cs&#39; file</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
{
    services.AddControllers(options =&gt
    {
        options.<span style="background:#f2f19d;">Filters.Add(<span class="key">new</span> <b>MyActionFilter</b>())</span>;
    });
}</code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Custom Filter Class</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span style="background:#f2f19d;">MyActionFilter</span> : IActionFilter
{
    <span class="key">public</span> <span class="key">void</span> OnActionExecuting(ActionExecutingContext context)
    {
        <span class="com">// Code before action executes</span>
    }

    <span class="key">public</span> <span class="key">void</span> OnActionExecuted(ActionExecutedContext context)
    {
        <span class="com">// Code after action executes</span>
    }
} </code></pre>

</div>
</div>
</li>


<li class="custp1"><strong>Controller-Level:</strong> Filters can be applied to specific controllers by using <strong>[TypeFilter]</strong> or <strong>[ServiceFilter]</strong> attributes on the controller class.
<div>
<button class="shbtn" id="shbtn56964" onclick="showHideBlock(56964)">&#9660; <u>Show example</u></button>
<div id="shdiv56964" style="display: none;">

<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span style="background:#f2f19d;">[ServiceFilter(<span class="key">typeof</span>(<b>MyActionFilter</b>))]</span>
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    [HttpGet]
    <span class="key">public</span> IActionResult GetProducts()
    {
        <span class="com">// ....</span>
    }
} </code></pre>

</div>
</div>
</li>


<li class="custp1"><strong>Action-Level:</strong> Filters can be applied to individual action methods by using <strong>[TypeFilter]</strong> or <strong>[ServiceFilter]</strong> attributes on the action method.
<div>
<button class="shbtn" id="shbtn13608" onclick="showHideBlock(13608)">&#9660; <u>Show example</u></button>
<div id="shdiv13608" style="display: none;">

<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    [HttpGet]
    <span style="background:#f2f19d;">[TypeFilter(<span class="key">typeof</span>(<b>MyActionFilter</b>))]</span>
    <span class="key">public</span> IActionResult GetProduct(<span class="key">int</span> id)
    {
        <span class="com">// ....</span>
    }
} </code></pre>

</div>
</div>
</li>


<li class="custp1"><strong>Middleware-Based Filters:</strong> Custom logic similar to filters can be implemented using middleware, which operates at the application level.
<div>
<button class="shbtn" id="shbtn67858" onclick="showHideBlock(67858)">&#9660; <u>Show example</u></button>
<div id="shdiv67858" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>In &#39;Startup.cs&#39; file</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMiddleware&lt;<span style="background:#f2f19d;">CustomMiddleware</span>&gt();

    app.UseRouting();
    <span class="com">// ....</span>
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Custom Middleware Class</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span style="background:#f2f19d;">CustomMiddleware</span>
{
    <span class="key">private</span> <span class="key">readonly</span> RequestDelegate _next;

    <span class="key">public</span> CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    <span class="key">public</span> <span class="key">async</span> Task InvokeAsync(HttpContext context)
    {
        <span class="com">// Pre-processing logic</span>
        context.Response.Headers.Add(<span class="str">"X-Custom-Middleware"</span>, <span class="str">"This is custom middleware"</span>);

        <span class="key">await</span> _next(context);

        <span class="com">// Post-processing logic</span>
    }
}</code></pre>

</div>
</div>
</li>

</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you configure Filters globally?</strong></h3>



<p class="custp1 p-mb-0">You can add global filters in the <strong>ConfigureServices</strong> method, in <strong>Startup.cs</strong> file.</p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
    {
        services.AddControllers(options =&gt
        {
            <span class="com">// Add global filters here</span>
            options.<span style="background:#f2f19d;">Filters.Add</span>(<span class="key">new</span> CustomActionFilter());
            options.<span style="background:#f2f19d;">Filters.Add</span>(<span class="key">new</span> AuthorizeFilter());
        });
    }
} </code></pre>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement content filtering in Web API?</strong></h3>



<p class="custp1 p-mb-0">There are different approaches to implementing content filtering in a Web API: </p>



<ol class="ol1 ol1-mb-0">
<li class="custp1"><strong>Creating custom &#39;Action Filter&#39;:</strong> You can create a custom action filter by implementing <span class="spanHT">IActionFilter</span> interface or deriving from <span class="spanHT">ActionFilterAttribute</span> class to inspect &amp; modify the content of request data before the action method is executed and then you can apply the custom filter globally, to specific controllers, or to individual actions.
<div>
<button class="shbtnlist" id="shbtn49120" onclick="showHideBlock(49120)">&#9660; <u>Show example</u></button>
<div id="shdiv49120" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;">
<b>Content Filtering by using &#39;ActionFilterAttribute&#39;</b>
<br><br>
<b>1.</b> Create a Custom Action Filter:
</div>

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span style="background:#f2f19d;">ContentFilter</span>Attribute : <span style="background:#f2f19d;">ActionFilterAttribute</span>
{
    <span class="key">public</span> <span class="key">override</span> <span class="key">void</span> OnActionExecuting(ActionExecutingContext context)
    {
        <span class="com">// Example: Filtering out offensive words</span>
        <span class="key">var</span> request = context.HttpContext.Request;
        <span class="key">if</span> (request.Method == HttpMethod.Post.ToString() || request.Method == HttpMethod.Put.ToString())
        {
            <span class="com">// Assuming the request content is JSON</span>
            <span class="key">var</span> content = <span class="key">new</span> StreamReader(request.Body).ReadToEnd();

            <span class="com">// Simple content filtering logic</span>
            <span style="background:#f2f19d;"><span class="key">if</span> (content.Contains(<span class="str">"offensiveWord"</span>))</span>
            {
                context.Result = <span class="key">new</span> BadRequestObjectResult(<span class="str">"Inappropriate content detected."</span>);
                return;
            }

            <span class="com">// Reset the request body stream after reading</span>
            <span class="key">var</span> memoryStream = <span class="key">new</span> MemoryStream();
            <span class="key">var</span> writer = <span class="key">new</span> StreamWriter(memoryStream);
            writer.Write(content);
            writer.Flush();
            memoryStream.Position = 0;
            request.Body = memoryStream;
        }

        base.OnActionExecuting(context);
    }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2.</b> Apply the Content Filter to Actions or Controllers:
<br>
<b>a)</b> To apply globally.
</div>

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
    {
        services.AddControllers(options =&gt
        {
            options.<span style="background:#f2f19d;">Filters.Add(<span class="key">new</span> ContentFilterAttribute()</span>); <span class="com">// Apply globally</span>
        });
    }
} </code></pre>

<br>
<b>b)</b> To apply to a Controller or Action.
<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> MessagesController : ControllerBase
{
    [<span class="custkey">HttpPost</span>]
    <span style="background:#f2f19d;">[ContentFilter]</span> <span class="com">// Apply to a specific action</span>
    <span class="key">public</span> IActionResult PostMessage([FromBody] <span class="key">string</span> message)
    {
        <span class="com">// The action logic</span>
        <span class="key">return</span> Ok(<span class="str">"Message received"</span>);
    }
} </code></pre>




</div>
</div>
</li>

<li class="custp1"><strong>Creating Custom Middleware:</strong> Alternatively, you can implement content filtering as middleware to have more control over the entire request and response process.
<div>
<button class="shbtnlist" id="shbtn87432" onclick="showHideBlock(87432)">&#9660; <u>Show example</u></button>
<div id="shdiv87432" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span style="background:#f2f19d;">ContentFilteringMiddleware</span>
{
    <span class="key">private</span> <span class="key">readonly</span> RequestDelegate _next;

    <span class="key">public</span> ContentFilteringMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    <span class="key">public</span> <span class="key">async</span> Task InvokeAsync(HttpContext context)
    {
        <span class="com">// Example: Check for inappropriate content in request body</span>
        context.Request.EnableBuffering();
        <span class="key">var</span> bodyAsText = <span class="key">await</span> <span class="key">new</span> StreamReader(context.Request.Body).ReadToEndAsync();

        <span style="background:#f2f19d;"><span class="key">if</span> (bodyAsText.Contains(<span class="str">"offensiveWord"</span>))</span>
        {
            context.Response.StatusCode = StatusCodes.Status400BadRequest;
            <span class="key">await</span> context.Response.WriteAsync(<span class="str">"Inappropriate content detected."</span>);
            return;
        }

        <span class="com">// Reset the request body stream position</span>
        context.Request.Body.Position = 0;

        <span class="com">// Call the next middleware in the pipeline</span>
        <span class="key">await</span> _next(context);
    }
}


<span class="com">// Register the middleware in the pipeline</span>
<span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.<b>UseMiddleware</b>&lt;<span style="background:#f2f19d;">ContentFilteringMiddleware&gt()</span>;

        app.UseRouting();
        app.UseEndpoints(endpoints =&gt
        {
            endpoints.MapControllers();
        });
    }
} </code></pre>

</div>
</div>
</li>

</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the differences between the [ServiceFilter] and [TypeFilter] attributes?</strong></h3>



<p class="custp1 p-mb-0"><strong>Service Filter:</strong> Filters can be applied to a controller or action method using Dependency Injection by using the <span class="spanHT">[ServiceFilter]</span> attribute, allowing the filter to access services from the DI container. Since the filter is resolved through the DI container, you can inject services into the filter&#8217;s constructor. This is useful when the filter needs to use services like logging, data access, or any other service registered in the DI container. The <span class="spanHT">[ServiceFilter]</span> attribute takes the type of the filter as a parameter. The filter is then resolved from the DI container and applied to the controller or action method where the attribute is used.</p>



<p class="custp1 p-mb-0"><strong>Type Filter:</strong> Filters can be applied to a controller or action method using the <span class="spanHT">[TypeFilter]</span> attribute, which allows passing parameters to the filter&#8217;s constructor using the &#8216;Arguments&#8217; property. Unlike <span class="spanHT">[ServiceFilter]</span>, which directly uses the DI container to resolve the filter, <span class="spanHT">[TypeFilter]</span> creates a new instance of the filter using the specified type. If the filter&#8217;s constructor has dependencies that are registered in the DI container, <span class="spanHT">[TypeFilter]</span> will resolve and inject those dependencies automatically. <span class="spanHT">[TypeFilter]</span> is particularly useful when you need to apply a filter with parameters that are not known until runtime. </p>



<p class="custp1 p-mb-0">Comparison of the <strong>[ServiceFilter]</strong> and <strong>[TypeFilter]</strong> attributes in a tabular format.</p>



<div style="height:18.75rem; overflow-y:scroll; border: 1px solid #d3d3d3;">
<table style="margin: 0;">
    <thead>
        <tr>
            <th>[ServiceFilter]</th>
            <th>[TypeFilter]</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Resolves the filter from the DI container.</td>
            <td>Creates a new instance of the filter using the specified type, with dependencies resolved from DI.</td>
        </tr>
        <tr>
            <td>Does not support passing parameters directly to the filter.</td>
            <td>Supports passing parameters to the filter’s constructor via the Arguments property.</td>
        </tr>
        <tr>
            <td>Use when the filter is already registered in the DI container and does not need runtime configuration.</td>
            <td>Use when you need to configure the filter at runtime with specific parameters.</td>
        </tr>
        <tr>
            <td>Reuses the same filter instance from the DI container, allowing scoped or singleton lifetimes.</td>
            <td>Creates a new instance of the filter for each request, potentially leading to transient behavior.</td>
        </tr>
        <tr>
            <td>Follows the lifetime specified in the DI container (e.g., Scoped, Singleton).</td>
            <td>Each request typically gets a new instance, regardless of the DI lifetime configuration.</td>
        </tr>
        <tr>
            <td><b>syntax:</b><pre class="pchl" style="margin-top: 5px !important;"><code>[<span class="custkey">ServiceFilter</span>(<span class="key">typeof</span>(MyFilter))] </code></pre></td>
            <td><b>syntax:</b><pre class="pchl" style="margin-top: 5px !important;"><code>[<span class="custkey">TypeFilter</span>(<span class="key">typeof</span>(MyFilter), Arguments = <span class="key">new</span> object[] { <span class="str">"param"</span> })] </code></pre></td>
        </tr>
    </tbody>
</table>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is URL rewriting and how do you implement it?</strong></h3>



<p class="custp1 p-mb-0"><strong>URL rewriting</strong> is a process where the URL requested by a client is transformed into another URL before it reaches the server&#8217;s request handler. This is often used for purposes such as improving SEO, providing clean and user-friendly URLs, or redirecting old URLs to new ones without changing the underlying resource. You need to add the URL rewriting middleware <span class="spanHT">UseRewriter()</span> in the request pipeline and define rules using <span class="spanHT">RewriteOptions</span>, in &#8216;Startup.cs&#8217; file.</p>



<button class="shbtn" id="shbtn19858" onclick="showHideBlock(19858)">&#9660; <u>Show example</u></button>
<div id="shdiv19858" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        <span class="com">// Define the rewrite options</span>
        <span class="key">var</span> rewriteOptions = <span style="background:#f2f19d;"><span class="key">new</span> RewriteOptions()</span>
            .AddRedirect(<span class="str">"old-url/(.*)"</span>, <span class="str">"new-url/$1"</span>)   <span class="com">// Redirect old URLs to new ones</span>
            .AddRewrite(@<span class="str">"^products/(\d+)"</span>, <span class="str">"api/products/$1"</span>, skipRemainingRules: <span class="key">true</span>); <span class="com">// Rewrite /products/{id} to /api/products/{id}</span>

        <span class="com">// Use the URL Rewriting middleware</span>
        app.<span style="background:#f2f19d;">UseRewriter(rewriteOptions)</span>;
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is [NonAction] attribute and how do you use it? </strong></h3>



<p class="custp1 p-mb-0">The <strong>[NonAction]</strong> attribute is used to indicate that a particular method in a controller is not an action method. If you don&#8217;t want it to be exposed as an API endpoint and cannot be called by HTTP requests, you can decorate it with the <span class="spanHT">[NonAction]</span> attribute</p>



<button class="shbtn" id="shbtn45426" onclick="showHideBlock(45426)">&#9660; <u>Show example</u></button>
<div id="shdiv45426" style="display: none;">


<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
	[HttpGet(<span class="str">"{id}"</span>)]
	<span class="key">public</span> IActionResult GetProduct(<span class="key">int</span> id)
	{
		<span class="com">// ....</span>
	}

	<span style="background:#f2f19d;">[NonAction]</span>
	<span class="key">public</span> <span class="key">string</span> FormatProductName(<span class="key">string</span> name)
	{
		<span class="com">// This is a utility method and should not be exposed as an API endpoint</span>
	}
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between IActionResult and ActionResult?</strong></h3>



<p class="custp1 p-mb-0">IActionResult and ActionResult are both used to define the return type of a controller action method, but they serve slightly different purposes and provide different levels of type safety and flexibility.</p>



<p class="custp1 p-mb-0"><strong>1) IActionResult</strong> is an interface that represents a result of an action method. It provides a contract for different types of HTTP responses, such as <span class="spanHT">OkResult</span>, <span class="spanHT">BadRequestResult</span>, <span class="spanHT">NotFoundResult</span>, etc. It is generally used when an action method can return different types of HTTP responses based on various conditions. Since it is not tied to a specific type, it offers flexibility but less type safety. </p>



<button class="shbtn" id="shbtn77933" onclick="showHideBlock(77933)">&#9660; <u>Show example</u></button>
<div id="shdiv77933" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span style="background:#f2f19d;">IActionResult</span> GetProduct(<span class="key">int</span> id)
{
    <span class="key">var</span> product = _productService.GetById(id);
    <span class="key">if</span> (product == <span class="key">null</span>)
    {
        <span class="key">return</span> <b>NotFound()</b>; <span class="com">// 404 Not Found</span>
    }
    <span class="key">return</span> <b>Ok(product)</b>; <span class="com">// 200 OK with the product data</span>
} </code></pre>
</div>



<p class="custp1 p-mb-0"><strong>2) ActionResult&lt;T&gt;</strong> is a generic class that inherits from <span class="spanHT">ActionResult</span> and wraps a response of type <span class="spanHT">T</span>. It combines the benefits of <span class="spanHT">IActionResult</span> with type safety by allowing the action to return either a specific type <span class="spanHT">T</span> or an <span class="spanHT">IActionResult</span>. It is used when you want to return either a specific object (like a model) or an HTTP response. This allows for strong typing, which is particularly useful for scenarios involving serialization of data.</p>



<button class="shbtn" id="shbtn59971" onclick="showHideBlock(59971)">&#9660; <u>Show example</u></button>
<div id="shdiv59971" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span style="background:#f2f19d;">ActionResult&lt;Product&gt</span> GetProduct(<span class="key">int</span> id)
{
    <span class="key">var</span> product = _productService.GetById(id);
    <span class="key">if</span> (product == <span class="key">null</span>)
    {
        <span class="key">return</span> <b>NotFound()</b>; <span class="com">// 404 Not Found</span>
    }
    <span class="key">return</span> <b>product</b>; <span class="com">// 200 OK with the product data</span>
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the different Service Lifetimes for Dependency Injection within ASP.NET Core?</strong></h3>



<p class="custp1 p-mb-0">There are <strong>3 different types of service lifetimes</strong> defined by the .NET Core DI framework.</p>



<ol class="ol1 ol1-mb-0">
<li class="custp1"><strong>Transient:</strong> A new instance is created every time the service is requested. This lifetime works best for lightweight, stateless services.
<div><i>syntax:</i> <span class="spanHT">AddTransient&lt;IService, Implementation>()</span></div>
</li>

<li class="custp1"><strong>Scoped:</strong> A new instance is created once per request.
<div><i>syntax:</i> <span class="spanHT">AddScoped&lt;IService, TImplementation>()</span></div>
</li>

<li class="custp1"><strong>Singleton:</strong> A single instance is created and shared throughout the application&#8217;s lifetime.
<div><i>syntax:</i> <span class="spanHT">AddSingleton&lt;IService, TImplementation>()</span></div>
</li>

</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you manage Dependency Injection in a Web API project?</strong></h3>



<p class="custp1 p-mb-0">Dependency Injection (DI) is a design pattern that helps in creating loosely coupled, testable, and maintainable applications by managing the dependencies of objects. In an ASP.NET Core Web API project, <strong><em>DI is a built-in feature</em></strong> that allows you to inject dependencies into your classes rather than hard-coding them. Dependency Injection in a Web API project involves:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Registering services</strong> in the Program.cs or Startup.cs file using <span class="spanHT">AddTransient</span>, <span class="spanHT">AddScoped</span>, or <span class="spanHT">AddSingleton</span>. </li>



<li><strong>Injecting dependencies</strong> into controllers, services, and middleware using constructor injection.</li>
</ul>



<button class="shbtn" id="shbtn47696" onclick="showHideBlock(47696)">&#9660; <u>Show example</u></button>
<div id="shdiv47696" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Constructor Dependency Injection Example:</b></div>
<pre class="pchl"><code><span class="com"><b>// 1. Create Interface</b></span>
<span class="key">public</span> <span class="key">interface</span> <span style="background:#f2f19d;">IMyService</span>
{
    <span class="key">void</span> GetAllProducts();
} 

<span class="com"><b>// 2. Implement Interface</b></span>
<span class="key">public</span> <span class="key">class</span> MyService : <span style="background:#f2f19d;">IMyService</span>
{
    <span class="key">public</span> <span class="key">void</span> GetAllProducts()
    {
        <span class="com">// Perform some operations</span>
    }
}

<span class="com"><b>// 3. Register Service</b></span>
<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="key">var</span> builder = WebApplication.CreateBuilder(args);

        <span class="com">// ...</span>

        <span class="com">// Register application services</span>
        builder.Services.<span style="background:#f2f19d;"><b>AddTransient</b>&lt;IMyService, MyService&gt()</span>;  <span class="com">// Transient lifetime</span>
        builder.Services.<b>AddScoped</b>&lt;IRepository, Repository&gt();  <span class="com">// Scoped lifetime</span>
        builder.Services.<b>AddSingleton</b>&lt;ILogger, Logger&gt();       <span class="com">// Singleton lifetime</span>

        <span class="com">// ....</span>
        app.Run();
    }
}


<span class="com"><b>// 4. Use Service</b></span>
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    <span class="key">private</span> <span class="key">readonly</span> <span style="background:#f2f19d;">IMyService</span> _myService;

    <span class="com">// Constructor injection</span>
    <span class="key">public</span> ProductsController(<span style="background:#f2f19d;">IMyService</span> myService)
    {
        _myService = myService;
    }

    [<span class="custkey">HttpGet</span>]
    <span class="key">public</span> IActionResult GetProducts()
    {
        <span class="key">var</span> products = <span style="background:#f2f19d;">_myService.GetAllProducts()</span>;
        <span class="key">return</span> Ok(products);
    }
}</code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is ModelState?</strong></h3>



<p class="custp1 p-mb-0"><strong>ModelState</strong> represents the state of model binding and validation for a request. Specifically, it is a dictionary that stores information about the validation errors that occurred during model binding. </p>



<p class="custp1 p-mb-0">The framework performs validation on the incoming data (e.g., checking required fields, data types, etc.).If any validation fails, the errors are stored in &#8216;ModelState&#8217;. </p>



<p class="custp1 p-mb-0">You can check if the &#8216;ModelState&#8217; is valid using <span class="spanHT">ModelState.IsValid</span> property. This ensures that only valid data is processed. </p>



<p class="custp1 p-mb-0">If &#8216;ModelState&#8217; is invalid(false), you can return a response with the validation errors, usually a &#8216;400 Bad Request&#8217;, along with the error details. </p>



<button class="shbtn" id="shbtn77935" onclick="showHideBlock(77935)">&#9660; <u>Show example</u></button>
<div id="shdiv77935" style="display: none;">

<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    [<span class="custkey">HttpPost</span>]
    <span class="key">public</span> IActionResult CreateProduct([FromBody] Product model)
    {
        <span class="com">// Check if the model state is valid</span>
        <span class="key">if</span> (!<span style="background:#f2f19d;">ModelState.IsValid</span>)
        {
            <span class="com">// Return a 400 Bad Request response with the validation errors</span>
            <span class="key">return</span> BadRequest(ModelState);
        }

        <span class="com">// Proceed with processing the valid model</span>
        <span class="com">// Logic to create the product...</span>
        <span class="key">return</span> Ok(<span class="str">"Product created successfully"</span>);
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you check or automate Model Validation?</strong></h3>



<p class="p-mb-0"><strong>(or) What are the different methods to apply ModelState in an application?</strong></p>



<p class="custp1 p-mb-0"><strong>ModelState</strong> can be checked manually in each action method or with an automatic approach which is generally applied globally. You can apply any approach according to your application needs to validate models in an application: </p>



<p class="custp1 p-mb-0"><strong>Different methods to apply ModelState:</strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Manual Action-Level Model Validation:</strong> You can check ModelState manually in each action method to ensure the model is valid before proceeding with the business logic.</li>



<li><strong>Automatic Model Validation:</strong> You can automatically validate ModelState and return errors globally, without the need to manually check ModelState in each action. You can implement it in two ways:
<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Using [ApiController] Attribute:</strong> The <span class="spanHT">[ApiController]</span> attribute automatically checks ModelState at the start of each request, before the controller action is invoked. If the model is invalid, it returns a &#8216;<strong>400 Bad Request</strong>&#8216; response with the validation errors. It automatically applies <strong>ModelStateInvalidFilter</strong>.</li>



<li><strong>Using Custom Filter:</strong> You can create a custom action filter using <span class="spanHT">IActionFilter</span> or <span class="spanHT">ActionFilterAttribute</span> to check the ModelState. It can be applied globally, to the specific controllers, or at each action level.</li>
</ul>
</li>
</ol>



<p class="custp1 p-mb-0">In any case, you need to create a Model property with validation rules using data annotations and for validation use <span class="spanHT">ModelState.IsValid</span> property to check if the model is valid.</p>



<button class="shbtn" id="shbtn98072" onclick="showHideBlock(98072)">&#9660; <u>Show example</u></button>
<div id="shdiv98072" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><h3><b>Steps to Implement Model Validation:</b></h3></div>
<br>
<div style="padding-left: 0.3125rem;">First, create Model properties specifying validation rules using data annotations, example:</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    [<span style="background:#f2f19d;">Required</span>(ErrorMessage = <span class="str">"Product name is required."</span>)]
    [<span style="background:#f2f19d;">StringLength</span>(100, ErrorMessage = <span class="str">"Product name cannot be longer than 100 characters."</span>)]
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    [<span style="background:#f2f19d;">Range</span>(1, 1000, ErrorMessage = <span class="str">"Price must be between 1 and 1000."</span>)]
    <span class="key">public</span> <span class="key">decimal</span> Price { get; set; }
} </code></pre>


<br><br><br>
<div style="padding-left: 0.3125rem;">Now, Validate Model using <b>ModelState.IsValid</b> property, manual or automatic approach.
<br> <br><h4><b>Method 1:  Manual Action-Level Model Validation</b></h4>
</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ProductsController : ApiController
{
    [HttpPost]
    <span class="key">public</span> IHttpActionResult CreateProduct(Product product)
    {
        <span class="key">if</span> (!<span style="background:#f2f19d;">ModelState.IsValid</span>)
        {
            <span class="key">return</span> BadRequest(ModelState); <span class="com">// Returns a 400 Bad Request with validation errors</span>
        }

        <span class="com">// Logic to save the product</span>
        <span class="key">return</span> Ok(product); <span class="com">// Returns a 200 OK response</span>
    }
} </code></pre>

<br><br><br>
<div style="padding-left: 0.3125rem;"><h4><b>Method 2: Automatic Model Validation</b></h4>
<br> <b>a) Using [ApiController] Attribute:</b>
</div>
<pre class="pchl"><code><span style="background:#f2f19d;">[ApiController]</span>
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> EventsController : ControllerBase
{
    [HttpPost]
    <span class="key">public</span> IActionResult CreateEvent([FromBody] Event newEvent)
    {
        <span style="background:#f2f19d;"><b>// No need to check ModelState manually; it&#39;s handled automatically.</b></span>
        <span class="key">return</span> Ok(<span class="str">"Event created successfully."</span>);
    }
} </code></pre>



<br><br>
<div style="padding-left: 0.3125rem;"><b>b) Using Custom Filter:</b></div>
<div style="padding-left: 0.3125rem;" class="custp1"><b>b.1)</b> Create action filter to handle model validation errors.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ValidateModelAttribute : <b>ActionFilterAttribute</b>
{
	<span class="key">public</span> <span class="key">override</span> <span class="key">void</span> OnActionExecuting(HttpActionContext actionContext)
	{
		<span class="key">if</span> (!actionContext.<span style="background:#f2f19d;">ModelState.IsValid</span>)
		{
			actionContext.Response = actionContext.Request.CreateErrorResponse(
				HttpStatusCode.BadRequest, actionContext.ModelState);
		}
	}
}</code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>b.2)</b> Apply the Custom Filter globally or alternatively to specific controllers or actions.
</div>
<div style="padding-left: 0.3125rem;" class="custp1"><b>b.2.a) At Global Level:</b> Model validation at global level. Register the filter globally in the &#39;ConfigureServices&#39; method, in &#39;Statup.cs&#39; file.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
    {
        services.AddControllers(options =&gt
        {
            <span class="com">// Add global filters here</span>
            options.<span style="background:#f2f19d;">Filters.Add(<span class="key">new</span> <b>ValidateModelAttribute()</b></span>);
        });
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>b.2.b) At Controller Level:</b> Model validation at contnroller level using the custom [ValidateModel] attribute.
</div>
<pre class="pchl"><code><span style="background:#f2f19d;">[ValidateModel]</span> <span class="com">// Apply at controller level</span>
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> EventsController : ControllerBase
{
    [HttpPost]
    <span class="key">public</span> IActionResult CreateEvent([FromBody] Event newEvent)
    {
        <span style="background:#f2f19d;">// ModelState is automatically validated</span>
        <span class="key">return</span> Ok(<span class="str">"Event created successfully."</span>);
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>b.2.c) At Action Level:</b> Model validation at action level using the custom [ValidateModel] attribute.
</div>
<pre class="pchl"><code>[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> EventsController : ControllerBase
{
    [HttpPost]
    <span style="background:#f2f19d;">[ValidateModel]</span> <span class="com">// Apply at action level</span>
    <span class="key">public</span> IActionResult CreateEvent([FromBody] Event newEvent)
    {
        <span style="background:#f2f19d;">// ModelState is automatically validated</span>
        <span class="key">return</span> Ok(<span class="str">"Event created successfully."</span>);
    }
} </code></pre>
</div>



<br><br><br><br>



<h2 class="wp-block-heading hLBRed"><strong>How to disable automatic Model State Validation?</strong></h2>



<p class="custp1 p-mb-0">Automatic ModelState validation can be disabled both at the global and action levels:</p>



<ul class="ol1 ol1-mb-0">

<li class="custp1"><strong>Using [SuppressModelStateInvalidFilter] property:</strong> The [SuppressModelStateInvalidFilter] is used to override the default behavior of automatic ModelState validation that comes with the [ApiController] attribute. You can use [SuppressModelStateInvalidFilter] globally or in scenarios where you want to handle ModelState validation manually for specific actions or controllers while still keeping the [ApiController] attribute on the controller.
<div>
<button class="shbtnlist" id="shbtn22536" onclick="showHideBlock(22536)">&#9660; <u>Show example</u></button>
<div id="shdiv22536" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>At Global Level:</b> In the Startup.cs file, modify the ConfigureServices method.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
	<span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
	{
		services.Configure&lt;<span class="custkey">ApiBehaviorOptions</span>&gt(options =&gt
		{
			<span class="com">// Disable the automatic model state validation</span>
			options.<span style="background:#f2f19d;">SuppressModelStateInvalidFilter = true</span>;
		});
	}
} </code></pre>

</div>
</div>
</li>

 
<li class="custp1"><strong>Removing the [ApiController] attribute:</strong> If you want to disable automatic ModelState validation for a specific action or controller while keeping it enabled globally, you can do so by removing the <strong>[ApiController]</strong> attribute from the controller and handling ModelState manually.
<div>
<button class="shbtnlist" id="shbtn67071" onclick="showHideBlock(67071)">&#9660; <u>Show example</u></button>
<div id="shdiv67071" style="display: none;">

<pre class="pchl"><code><span style="background:#f2f19d;">// Simply remove the <b>[ApiController]</b> attribute from the controller</span>
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> EventsController : ControllerBase
{
    [HttpPost]
    <span class="key">public</span> IActionResult CreateEvent([FromBody] Event newEvent)
    {
        <span style="background:#f2f19d;">// Manual ModelState check</span>
        <span class="key">if</span> (!<b>ModelState.IsValid</b>)
        {
            <span class="key">return</span> BadRequest(ModelState);
        }

        <span class="key">return</span> Ok(<span class="str">"Event created successfully."</span>);
    }
} </code></pre>

</div>
</div>
</li>

</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How to create Custom Data Annotation Validators?</strong></h3>



<p class="custp1 p-mb-0">You can create a custom validation attribute by inheriting from <span class="spanHT">ValidationAttribute</span> and override the <span class="spanHT">IsValid</span> method to implement custom validation logic. Apply the custom attribute to the model properties that need validation. Validate the model in your API controller and handle invalid models appropriately.</p>



<button class="shbtn" id="shbtn18389" onclick="showHideBlock(18389)">&#9660; <u>Show example</u></button>
<div id="shdiv18389" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;">In this example, creating a custom data annotation validator that accepts only AlphaNumeric value.
<br><br><b>1. Create a Custom Validation Attribute.</b></div>
<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.ComponentModel.DataAnnotations;
<span class="key">using</span> System.Text.RegularExpressions;

<span class="key">public</span> <span class="key">class</span> Alphanumeric : <span style="background:#f2f19d;">ValidationAttribute</span>
{
    <span class="key">public</span> <span class="key">override</span> <span class="key">bool</span> IsValid(Object value)
    {
        <span class="key">if</span> (Regex.IsMatch(value.ToString(), <span class="str">"^[a-zA-Z0-9]*$"</span>))
        {
            <span class="key">return</span> true;
        }
        <span class="key">return</span> false;
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Apply the Custom Validator to a Model.</b></div>
<pre class="pchl"><code><span style="background:#f2f19d;">[<span class="custkey"><b>Alphanumeric</b></span>(ErrorMessage = <span class="str">"Code only accecpts alpha numeric value."</span>)]</span>
<span class="key">public</span> <span class="key">string</span> Code { get; set; } </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>3. Use the Model:</b>
<br>
<b>Method 1:</b> In a Controller, particularly for create or update request.
</div>
<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> EventsController : ControllerBase
{
    [HttpPost]
    <span class="key">public</span> IActionResult CreateEvent([FromBody] Event newEvent)
    {
        <span style="background:#f2f19d;"><span class="key">if</span> (!<b>ModelState.IsValid</b>)</span>
        {
            <span class="key">return</span> BadRequest(ModelState);
        }

        <span class="com">// Logic to save the event</span>
        <span class="key">return</span> Ok(<span class="str">"Event created successfully."</span>);
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Method 2:</b> Optionally, you can use a global action filter to handle model validation errors centrally, to avoid repetitive validation checks in every action.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ValidationFilterAttribute : IActionFilter
{
    <span class="key">public</span> <span class="key">void</span> OnActionExecuted(ActionExecutedContext context)
    {
        return;
    }

    <span class="key">public</span> <span class="key">void</span> OnActionExecuting(ActionExecutingContext context)
    {
        <span class="com">// custom json error response result.</span>	
        ResultObject resultDto = <span class="key">new</span> ResultObject();

        <span style="background:#f2f19d;"><span class="key">if</span> (!context.<b>ModelState.IsValid</b>)</span>
        {
            resultDto.ErrorMessage = string.Join(Environment.NewLine, context.ModelState.Values.SelectMany(x =&gt x.Errors).Select(x =&gt x.ErrorMessage));
            resultDto.HasError = true;
            resultDto.ResponseCode = 400;
            context.Result = <span class="key">new</span> JsonResult(resultDto);

            context.HttpContext.Response.StatusCode = 400;
        }
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a message handler, and how do you use it in Web API?</strong></h3>



<p class="custp1 p-mb-0"><strong>Message handlers</strong> in Web API are components that process HTTP requests and responses. They act as a pipeline, allowing you to intercept, process, or modify HTTP messages before they reach the controller or after they leave it. Message handlers are particularly useful for tasks like logging, authentication, or custom request processing. You create a custom handler by inheriting from <span class="spanHT">DelegatingHandler</span> and registering it in the Web API configuration.</p>



<button class="shbtn" id="shbtn25365" onclick="showHideBlock(25365)">&#9660; <u>Show example</u></button>
<div id="shdiv25365" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1) Create a Custom Message Handler:</b>
<br>
Derive a class from <b>DelegatingHandler</b> and override the <b>SendAsync</b> method to process the request.
</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> CustomMessageHandler : <span style="background:#f2f19d;">DelegatingHandler</span>
{
    <span class="key">protected</span> <span class="key">override</span> <span class="key">async</span> Task&lt;HttpResponseMessage&gt <span style="background:#f2f19d;">SendAsync</span>(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        <span class="com">// Pre-processing logic (e.g., logging)</span>
        <span class="key">var</span> requestInfo = $<span class="str">"Method: {request.Method}, URI: {request.RequestUri}"</span>;
        Console.WriteLine($<span class="str">"Request: {requestInfo}"</span>);

        <span class="com">// Call the inner handler to continue processing</span>
        <span class="key">var</span> response = <span class="key">await</span> base.SendAsync(request, cancellationToken);

        <span class="com">// Post-processing logic (e.g., modifying response)</span>
        response.Headers.Add(<span class="str">"X-Custom-Header"</span>, <span class="str">"CustomHeaderValue"</span>);

        <span class="key">return</span> response;
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2) Register the Message Handler in Web API configuration:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">static</span> <span class="key">class</span> WebApiConfig
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Register(HttpConfiguration config)
    {
        <span class="com">// Register the custom message handler</span>
        <span style="background:#f2f19d;">config.MessageHandlers.Add(<span class="key">new</span> CustomMessageHandler());</span>
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are different strategies to protect Web API in .NET?</strong></h3>



<p class="custp1 p-mb-0">Securing a Web API in .NET involves a combination of <span class="spanHT">authentication</span>, <span class="spanHT">authorization</span>, <span class="spanHT">HTTPS enforcement</span>, <span class="spanHT">CORS configuration</span>, <span class="spanHT">data validation</span>, <span class="spanHT">rate limiting</span>, <span class="spanHT">logging</span>, and <span class="spanHT">monitoring</span>. Together, these strategies ensure that your API is protected against unauthorized access and potential threats.</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Authentication:</strong> Verify the identity of the user or system accessing the API like, 
<ul class="wp-block-list">
<li><strong>JWT (JSON Web Tokens)</strong>: Use tokens to authenticate requests. Clients include the token in the Authorization header.</li>



<li><strong>OAuth2/OpenID Connect</strong>: Implement industry-standard protocols for token-based authentication.</li>



<li><strong>API Keys</strong>: Simple method where clients include a key in their requests.</li>
</ul>
</li>



<li><strong>Authorization:</strong> Control what authenticated users can access or do.
<ul class="wp-block-list">
<li><strong>Role-Based Authorization</strong>: Define user roles and restrict access to certain endpoints based on these roles.</li>



<li><strong>Policy-Based Authorization</strong>: Create custom authorization policies based on complex conditions. </li>
</ul>
</li>



<li><strong>HTTPS (SSL/TLS):</strong> Configure the server to enforce HTTPS, ensuring that all communication between the client and server is encrypted.</li>



<li class="custp1"><strong>CORS (Cross-Origin Resource Sharing):</strong> Restrict which domains can access your API from a browser. Define allowed origins, methods, and headers in your API configuration.</li>



<li class="custp1"><strong>Data Validation and Sanitization:</strong> Validate and sanitize incoming data to protect against injection attacks. Use model validation attributes and sanitize inputs where necessary.</li>



<li class="custp1"><strong>Rate Limiting and Throttling:</strong> Limit the number of requests a client can make in a given time frame to protect against abuse. Use middleware or external services to enforce rate limits.</li>



<li class="custp1"><strong>Logging and Monitoring:</strong> Track API usage and detect suspicious activities. Integrate logging frameworks like Serilog and monitoring tools like Application Insights.</li>



<li class="custp1"><strong>Anti-Forgery Tokens:</strong> Protect against Cross-Site Request Forgery (CSRF) attacks. Use anti-forgery tokens in state-changing requests (e.g., POST, PUT).</li>
</ol>



<button class="shbtn" id="shbtn37584" onclick="showHideBlock(37584)">&#9660; <u>Show example</u></button>
<div id="shdiv37584" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Authentication example with JWT:</b></div>
<pre class="pchl"><code>services.<span style="background:#f2f19d;">AddAuthentication(JwtBearerDefaults.AuthenticationScheme)</span>
        .AddJwtBearer(options =&gt
        {
            options.TokenValidationParameters = <span class="key">new</span> TokenValidationParameters
            {
                ValidateIssuer = <span class="key">true</span>,
                ValidateAudience = <span class="key">true</span>,
                ValidateLifetime = <span class="key">true</span>,
                ValidateIssuerSigningKey = <span class="key">true</span>,
                ValidIssuer = <span class="str">"yourIssuer"</span>,
                ValidAudience = <span class="str">"yourAudience"</span>,
                IssuerSigningKey = <span class="key">new</span> SymmetricSecurityKey(Encoding.UTF8.GetBytes(<span class="str">"yourSecretKey"</span>))
            };
        }); </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Authorization example:</b></div>
<pre class="pchl"><code><span style="background:#f2f19d;">[Authorize(Roles = <span class="str">"Admin"</span>)]</span>
<span class="key">public</span> IActionResult GetSensitiveData()
{
    <span class="key">return</span> Ok(<span class="str">"Sensitive data only for Admins."</span>);
} </code></pre>



<br><br>
<div style="padding-left: 0.3125rem;"><b>3. HTTPS (SSL/TLS) configuration:</b>
<br>
<span class="custp1">In <b>Program.cs</b>, enforce HTTPS redirection.</span>
</div>
<pre class="pchl"><code>app.UseHttpsRedirection(); </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>4. CORS configuration:</b></div>
<pre class="pchl"><code>services.<span style="background:#f2f19d;">AddCors</span>(options =&gt
{
    options.AddPolicy(<span class="str">"AllowSpecificOrigin"</span>,
        builder =&gt builder.WithOrigins(<span class="str">"https://example.com"</span>)
                          .AllowAnyMethod()
                          .AllowAnyHeader());
});

app.<span style="background:#f2f19d;">UseCors</span>(<span class="str">"AllowSpecificOrigin"</span>); </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>5. Data Validation example:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    <span style="background:#f2f19d;">[Required]</span>
    <span style="background:#f2f19d;">[StringLength(100)]</span>
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span style="background:#f2f19d;">[Range(0, 1000)]</span>
    <span class="key">public</span> <span class="key">decimal</span> Price { get; set; }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>6. Rate Limiting and Throttling configuration:</b></div>
<pre class="pchl"><code>services.<span style="background:#f2f19d;">AddRateLimiting</span>(options =&gt
{
    options.GlobalRateLimit = <span class="key">new</span> RateLimitRule
    {
        Period = <span class="str">"1m"</span>,
        Limit = 100
    };
}); </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>7. Logging and Monitoring (Application Insight configuration):</b></div>
<pre class="pchl"><code>services.AddApplicationInsightsTelemetry(); </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>8. Anti-Forgery Tokens configuration:</b></div>
<pre class="pchl"><code>services.<span style="background:#f2f19d;">AddAntiforgery</span>(options =&gt 
{
    options.HeaderName = <span class="str">"X-XSRF-TOKEN"</span>;
}); </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement Custom Authorization filters in Web API?</strong></h3>



<p class="custp1 p-mb-0">Custom authorization filters allow you to enforce specific security requirements before an action method is executed. These filters can be used to implement custom logic to determine whether a user or request should be allowed to proceed. </p>



<p class="custp1 p-mb-0"><strong><em>Steps to Implement Custom Authorization Filters:</em></strong></p>



<ol class="ol1 ol1-mb-0">
<li class="custp1"><strong>Create a Custom Authorization Filter:</strong> Implement the <span class="spanHT">IAuthorizationFilter</span> interface or derive from <span class="spanHT">AuthorizeAttribute</span> to create a custom authorization filter.
<div>
<button class="shbtnlist" id="shbtn6270" onclick="showHideBlock(6270)">&#9660; <u>Show example</u></button>
<div id="shdiv6270" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span style="background:#f2f19d;">CustomAuthorize</span>Attribute : <span style="background:#f2f19d;">AuthorizeAttribute, IAuthorizationFilter</span>
{
    <span class="key">public</span> <span class="key">void</span> OnAuthorization(AuthorizationFilterContext context)
    {
        <span class="com">// Custom logic to check if the user is authorized</span>
        <span class="key">var</span> isAuthenticated = context.HttpContext.User.Identity.IsAuthenticated;

        <span class="key">if</span> (!isAuthenticated)
        {
            <span class="com">// If the user is not authorized, set the result to 401 Unauthorized</span>
            context.Result = <span class="key">new</span> UnauthorizedResult();
        }
        <span class="com">// Add more custom checks here if needed</span>
    }
} </code></pre>

</div>
</div>
</li>


<li class="custp1"><strong>Apply the Custom Authorization Filter:</strong> Apply the filter to controllers or actions by using the <span class="spanHT">[CustomAuthorize]</span> attribute.
<div>
<button class="shbtnlist" id="shbtn11111" onclick="showHideBlock(11111)">&#9660; <u>Show example</u></button>
<div id="shdiv11111" style="display: none;" class="shdt">
<br>
<div style="padding-left: 0.3125rem;"><b>Method 1:</b> In Action level.</div>
<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> SecureController : ControllerBase
{
    [<span class="custkey">HttpGet</span>]
    <span style="background:#f2f19d;">[CustomAuthorize]</span> <span class="com">// Apply the custom authorization filter</span>
    <span class="key">public</span> IActionResult GetSecureData()
    {
        <span class="key">return</span> Ok(<span class="str">"This is secured data"</span>);
    }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>Method 2:</b> Optionally, if you want the custom authorization to apply globally to all controllers, register it in the Startup.cs or Program.cs.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
    {
        services.AddControllers(options =&gt
        {
            options.<span style="background:#f2f19d;">Filters.Add(<span class="key">new</span> CustomAuthorizeAttribute())</span>; <span class="com">// Register globally</span>
        });
    }
} </code></pre>

</div>
</div>

</li>

</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle Authorization in a Web API using Policies?</strong></h3>



<p class="p-mb-0"><strong>How do you implement a Custom authorization Handler?</strong> (See &#8216;Method 2&#8217; in the example).</p>



<p class="custp1 p-mb-0">Authorization in a Web API using policies allows you to implement fine-grained access control by defining rules (policies) that determine whether a user is authorized to access specific resources or perform specific actions. Policies are defined in the &#8216;Program.cs&#8217; or &#8216;Startup.cs&#8217; file, and they can be based on roles, claims, or custom logic. You apply these policies using the <span class="spanHT">[Authorize]</span> attribute on controllers or actions, and you can also create custom authorization requirements for more complex scenarios.</p>



<button class="shbtn" id="shbtn79354" onclick="showHideBlock(79354)">&#9660; <u>Show example</u></button>
<div id="shdiv79354" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;">
<h3><b>Method 1:</b> General Approach</h3>
<br>
<b>a)</b> Define Policies in Program.cs or Startup.cs file.
</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="key">var</span> builder = WebApplication.CreateBuilder(args);

        <span class="com">// Add services to the container.</span>
        builder.Services.AddControllers();

        <span class="com">// Add authorization policies</span>
        builder.Services.AddAuthorization(options =&gt
        {
            options.<span style="background:#f2f19d;">AddPolicy</span>(<span class="str">"AdminOnly"</span>, policy =&gt
                policy.RequireRole(<span class="str">"Admin"</span>));

            options.<span style="background:#f2f19d;">AddPolicy</span>(<span class="str">"Over18Only"</span>, policy =&gt
                policy.RequireClaim(<span class="str">"Age"</span>, <span class="str">"18"</span>));

            options.<span style="background:#f2f19d;">AddPolicy</span>(<span class="str">"CustomPolicy"</span>, policy =&gt
                policy.RequireAssertion(context =&gt
                    context.User.HasClaim(c =&gt c.Type == <span class="str">"Permission"</span> && c.Value == <span class="str">"CanAccessResource"</span>)));
        });

        <span class="key">var</span> app = builder.Build();

        <span class="com">// Configure the HTTP request pipeline.</span>
        app.UseAuthorization();

        app.MapControllers();

        app.Run();
    }
} </code></pre>

<br><br>
<b>b)</b> Use the [Authorize] attribute with the Policy property to enforce the policy on controllers or specific actions.
<br>
<pre class="pchl"><code><span style="background:#f2f19d;">[Authorize(Policy = <span class="str">"AdminOnly"</span>)]</span>
[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> AdminController : ControllerBase
{
    [HttpGet]
    <span class="key">public</span> IActionResult GetAdminData()
    {
        <span class="key">return</span> Ok(<span class="str">"This is admin data."</span>);
    }
}

<span style="background:#f2f19d;">[Authorize(Policy = <span class="str">"Over18Only"</span>)]</span>
[HttpGet]
[Route(<span class="str">"api/age-restricted"</span>)]
<span class="key">public</span> IActionResult GetAgeRestrictedData()
{
    <span class="key">return</span> Ok(<span class="str">"This content is restricted to users over 18."</span>);
}

<span style="background:#f2f19d;">[Authorize(Policy = <span class="str">"CustomPolicy"</span>)]</span>
[HttpGet]
[Route(<span class="str">"api/custom-resource"</span>)]
<span class="key">public</span> IActionResult GetCustomResource()
{
    <span class="key">return</span> Ok(<span class="str">"This is a resource protected by a custom policy."</span>);
} </code></pre>



<br><br><br>
<div style="padding-left: 0.3125rem;">
<h3><b>Method 2:</b> Custom Authorization Requirements or Handler</h3>
<br>
You can create custom authorization requirements if you need more complex logic.
</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> MinimumAgeRequirement : <span style="background:#f2f19d;">IAuthorizationRequirement</span>
{
    <span class="key">public</span> <span class="key">int</span> MinimumAge { get; }

    <span class="key">public</span> MinimumAgeRequirement(<span class="key">int</span> minimumAge)
    {
        MinimumAge = minimumAge;
    }
}

<span class="key">public</span> <span class="key">class</span> <span style="background:#f2f19d;">MinimumAgeHandler</span> : <span style="background:#f2f19d;">AuthorizationHandler&lt;MinimumAgeRequirement&gt</span>
{
    <span class="key">protected</span> <span class="key">override</span> Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                   MinimumAgeRequirement requirement)
    {
        <span class="key">var</span> userBirthDate = context.User.FindFirst(c =&gt c.Type == ClaimTypes.DateOfBirth);
        <span class="key">if</span> (userBirthDate != <span class="key">null</span>)
        {
            <span class="key">var</span> birthDate = Convert.ToDateTime(userBirthDate.Value);
            <span class="key">int</span> calculatedAge = DateTime.Today.Year - birthDate.Year;
            <span class="key">if</span> (calculatedAge &gt= requirement.MinimumAge)
            {
                context.Succeed(requirement);
            }
        }
        <span class="key">return</span> Task.CompletedTask;
    }
}</code></pre>


<br><br>
<div style="padding-left: 0.3125rem;">Register the custom requirement and handler in Program.cs or Startup.cs</div>
<pre class="pchl"><code>builder.Services.AddAuthorization(options =&gt
{
    options.<span style="background:#f2f19d;">AddPolicy</span>(<span class="str">"AtLeast21"</span>, policy =&gt
        policy.Requirements.Add(<span class="key">new</span> MinimumAgeRequirement(21)));
});

builder.Services.AddSingleton&lt;<span style="background:#f2f19d;">IAuthorizationHandler</span>, <span style="background:#f2f19d;">MinimumAgeHandler&gt()</span>; </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is OAuth?</strong></h3>



<p class="custp1 p-mb-0">OAuth (Open Authorization) is an open standard for token-based authentication and authorization, allowing third-party applications to access user data from another service (like Google, Facebook, or Twitter) without exposing the user&#8217;s credentials (e.g., username and password). OAuth is commonly used to grant secure access to APIs on behalf of a user, using access tokens rather than sharing login credentials. </p>



<p class="custp1 p-mb-0">OAuth is commonly used for single sign-on (SSO) and for authorizing applications to interact with APIs on behalf of a user. </p>



<p class="custp1 p-mb-0"><strong><em>The OAuth flow typically involves:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1">The <em>client</em> requests authorization from the <em>resource owner</em>.</li>



<li>The resource owner grants access and the <em>authorization server</em> issues an access token to the client.</li>



<li>The client uses this <em>token to access the resource</em> server.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is JWT?</strong></h3>



<p class="custp1 p-mb-0"><strong>JWT (JSON Web Token)</strong> is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. JWTs are widely used for authentication and authorization in web applications and APIs. They are compact, URL-safe, and can be easily transmitted between a client and a server.</p>



<p class="custp1 p-mb-0"><strong><em>A JWT consists of three parts:</em></strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Header</strong>: Contains metadata about the token, including the type of token (JWT) and the signing algorithm used (e.g., HMAC SHA256).</li>



<li><strong>Payload</strong>: Contains the claims, which are statements about an entity (typically, the user) and additional data. Common claims include <strong>sub</strong> (subject, usually the user ID), <strong>exp</strong> (expiration time), and <strong>iat</strong> (issued at time).</li>



<li><strong>Signature</strong>: Ensures that the token hasn&#8217;t been altered. It&#8217;s created by signing the header and payload using a secret key and the specified algorithm.</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you secure a Web API using JWT?</strong></h3>



<p class="custp1 p-mb-0">To <strong>secure a Web API using JWT</strong>, you need to follow these steps:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Generate a JWT on User Authentication:</strong> When a user successfully authenticates (e.g., by providing a username and password), the server generates a JWT containing the user&#8217;s claims. The server then sends this token back to the client.
<div>
<button class="shbtnlist" id="shbtn40840" onclick="showHideBlock(40840)">▼ <u>Show example</u></button>
<div id="shdiv40840" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">string</span> GenerateJwtToken(<span class="key">string</span> username)
{
    <span class="key">var</span> claims = new[]
    {
        <span class="key">new</span> Claim(JwtRegisteredClaimNames.Sub, username),
        <span class="key">new</span> Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
    };

    <span class="key">var</span> key = <span class="key">new</span> SymmetricSecurityKey(Encoding.UTF8.GetBytes(<span class="str">"your_secret_key"</span>));
    <span class="key">var</span> creds = <span class="key">new</span> SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    <span class="key">var</span> token = <span class="key">new</span> JwtSecurityToken(
        issuer: <span class="str">"yourIssuer"</span>,
        audience: <span class="str">"yourAudience"</span>,
        claims: claims,
        expires: DateTime.Now.AddMinutes(30),
        signingCredentials: creds);

    <span class="key">return</span> <span class="key">new</span> JwtSecurityTokenHandler().WriteToken(token);
} </code></pre>


</div>
</div>
</li>



<li class="custp1"><strong>Client Stores and Sends JWT:</strong> The client (e.g., a web or mobile app) stores the JWT, typically in local storage or a cookie. For each subsequent API request, the client includes the JWT in the <strong>Authorization</strong> header as a Bearer token. <div> <button class="shbtnlist" id="shbtn94244" onclick="showHideBlock(94244)">▼ <u>Show example</u></button> <div id="shdiv94244" style="display: none;"> 
<pre class="pchl"><code>GET /api/products
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... </code></pre> </div> </div> </li>



<li class="custp1"><strong>Configure JWT Authentication in the Web API:</strong> In your ASP.NET Core Web API, configure the JWT authentication middleware to validate incoming tokens.
<div>
<button class="shbtnlist" id="shbtn41815" onclick="showHideBlock(41815)">▼ <u>Show example</u></button>
<div id="shdiv41815" style="display: none;">

<pre class="pchl"><code>services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =&gt;
        {
            options.TokenValidationParameters = <span class="key">new</span> TokenValidationParameters
            {
                ValidateIssuer = <span class="key">true</span>,
                ValidateAudience = <span class="key">true</span>,
                ValidateLifetime = <span class="key">true</span>,
                ValidateIssuerSigningKey = <span class="key">true</span>,
                ValidIssuer = <span class="str">"yourIssuer"</span>,
                ValidAudience = <span class="str">"yourAudience"</span>,
                IssuerSigningKey = <span class="key">new</span> SymmetricSecurityKey(Encoding.UTF8.GetBytes(<span class="str">"your_secret_key"</span>))
            };
        }); </code></pre>

</div>
</div>
</li>



<li class="custp1"><strong>Protect API Endpoints:</strong> Use the <strong>[Authorize]</strong> attribute to secure your API endpoints, ensuring that only authenticated users with a valid JWT can access them. <div> <button class="shbtnlist" id="shbtn91311" onclick="showHideBlock(91311)">▼ <u>Show example</u></button> <div id="shdiv91311" style="display: none;"> 
<pre class="pchl"><code>[Authorize]
[HttpGet]
<span class="key">public</span> IActionResult GetSecureData()
{
    <span class="key">return</span> Ok(<span class="str">"This is protected data."</span>);
} </code></pre> 
</div> </div> </li>



<li class="custp1"><strong>Handle Token Expiration and Refresh:</strong> JWTs typically have an expiration time (e.g., 30 minutes). When the token expires, the client should either re-authenticate or use a refresh token to obtain a new JWT.</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you enforce SSL/TLS in a Web API?</strong></h3>



<p class="custp1 p-mb-0">You can use following steps to enforce SSL/TLS to ensures that all data transmitted between the client and server is encrypted, providing a secure communication channel.</p>



<ol class="ol1 ol1-mb-0">
<li class="custp1"><strong>Using &#39;UseHttpsRedirection&#39; &amp; Enabling &#39;HSTS&#39;:</strong> Use the <span class="spanHT">UseHttpsRedirection</span> middleware to automatically redirect HTTP requests to HTTPS and enable HSTS(HTTP Strict Transport Security) using the <span class="spanHT">UseHsts</span> middleware to ensure all communication is done over HTTPS, in Startup.cs file.

<div>
<button class="shbtnlist" id="shbtn85489" onclick="showHideBlock(85489)">&#9660; <u>Show example</u></button>
<div id="shdiv85489" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        <span class="key">if</span> (!env.IsDevelopment())
        {
            <span class="com">// Redirect HTTP requests to HTTPS</span>
            app.<span style="background:#f2f19d;">UseHttpsRedirection()</span>; 
			
            <span class="com">// Add HTTP Strict Transport Security (HSTS) headers</span>
            app.<span style="background:#f2f19d;">UseHsts()</span>; 
        }
		
		<span class="com">// ....</span>
    }
} </code></pre>

</div>
</div>
</li>


<li class="custp1"><strong>Configure HTTPS in &#39;launchSettings.json&#39;</strong> Ensure that HTTPS is enabled in the <span class="spanHT">launchSettings.json</span> file, which is used during development to configure how the application is launched.
<div>
<button class="shbtnlist" id="shbtn48674" onclick="showHideBlock(48674)">&#9660; <u>Show example</u></button>
<div id="shdiv48674" style="display: none;" class="shdt">

<pre class="pchl"><code>{
  <span class="str">"profiles"</span>: {
    <span class="str">"IIS Express"</span>: {
      <span class="str">"commandName"</span>: <span class="str">"IISExpress"</span>,
      <span class="str">"launchBrowser"</span>: <span class="key">true</span>,
      <span class="str">"environmentVariables"</span>: {
        <span class="str">"ASPNETCORE_ENVIRONMENT"</span>: <span class="str">"Development"</span>
      },
      <span style="background:#f2f19d;"><span class="str">"sslPort"</span>: 44356</span>
    },
    <span class="str">"WebAPI"</span>: {
      <span class="str">"commandName"</span>: <span class="str">"Project"</span>,
      <span class="str">"launchBrowser"</span>: <span class="key">true</span>,
      <span style="background:#f2f19d;"><span class="str">"applicationUrl"</span></span>: <span class="str">"<span style="background:#f2f19d;">https</span>://localhost:5001;http://localhost:5000"</span>,
      <span class="str">"environmentVariables"</span>: {
        <span class="str">"ASPNETCORE_ENVIRONMENT"</span>: <span class="str">"Development"</span>
      }
    }
  }
} </code></pre>

<div style="padding-left: 0.3125rem;" class="custp1">The <span class="spanHT">sslPort</span> defines the port on which HTTPS is served. <br>The <span class="spanHT">applicationUrl</span> contains both HTTP and HTTPS URLs.</div>


</div>
</div>
</li>


<li class="custp1"><strong>Require HTTPS Globally:</strong> Optionally, use <span class="spanHT">[RequireHttps]</span> attribute to enforce HTTPS on specific controllers or actions.
<div>
<button class="shbtnlist" id="shbtn31738" onclick="showHideBlock(31738)">&#9660; <u>Show example</u></button>
<div id="shdiv31738" style="display: none;">

<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span style="background:#f2f19d;">[RequireHttps]</span> <span class="com">// Enforce HTTPS on all actions within this controller</span>
<span class="key">public</span> <span class="key">class</span> SecureController : ControllerBase
{
    [<span class="custkey">HttpGet</span>]
    <span class="key">public</span> IActionResult GetSecureData()
    {
        <span class="key">return</span> Ok(<span class="str">"This data is served over HTTPS"</span>);
    }
} </code></pre>

</div>
</div>
</li>

</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement HTTP caching in Web API?</strong></h3>



<p class="custp1 p-mb-0">Implementing HTTP caching in a Web API can significantly improve performance by reducing the load on the server and decreasing the response time for clients. HTTP caching allows responses to be stored temporarily (cached) by clients or intermediate proxies, so subsequent requests can be served from the cache instead of recomputing the response. </p>



<p class="custp1 p-mb-0">HTTP caching in Web API can be implemented using several techniques:</p>



<ol class="ol1 ol1-mb-0">
<li class="custp1"><strong>Cache-Control Header:</strong> The Cache-Control header is used to specify directives for caching mechanisms in both requests and responses.
</li>
<div> 
<button class="shbtnlist" id="shbtn14930" onclick="showHideBlock(14930)">▼ <u>Show example</u></button> 
<div id="shdiv14930" style="display: none;"> 
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ProductsController : ApiController
{
    [<span class="custkey">HttpGet</span>]
    [Route(<span class="str">"api/products"</span>)]
    <span class="key">public</span> IHttpActionResult GetProducts()
    {
        <span class="key">var</span> products = GetProductsFromDatabase();

        <span class="com">// Set Cache-Control header for 60 seconds</span>
        <span>HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);</span>
        <span>HttpContext.Current.Response.Cache.SetMaxAge(TimeSpan.FromSeconds(60));</span>

        <span class="key">return</span> Ok(products);
    }
} </code></pre>
</div> 
</div>



<li class="custp1"><strong>Expires header:</strong> The Expires header specifies a date and time after which the response is considered stale. 
</li>
<div> 
<button class="shbtnlist" id="shbtn7239" onclick="showHideBlock(7239)">▼ <u>Show example</u></button> 
<div id="shdiv7239" style="display: none;"> 
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ProductsController : ApiController
{
    [<span class="custkey">HttpGet</span>]
    [Route(<span class="str">"api/products"</span>)]
    <span class="key">public</span> IHttpActionResult GetProducts()
    {
        <span class="key">var</span> products = GetProductsFromDatabase();

        <span class="com">// Set the Expires header</span>
        HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(5));
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);

        <span class="key">return</span> Ok(products);
    }
} </code></pre>
</div> 
</div>



<li class="custp1"><strong>OutputCache Attribute:</strong> The <strong>[OutputCache]</strong> attribute can be used to cache the output of an action method. However, it&#8217;s important to note that this is specific to ASP.NET Web API 2 and earlier versions.
</li>
<div>
<button class="shbtnlist" id="shbtn80631" onclick="showHideBlock(80631)">▼ <u>Show example</u></button>
<div id="shdiv80631" style="display: none;" class="shdt">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ProductsController : ApiController
{
    [<span class="custkey">HttpGet</span>]
    [Route(<span class="str">"api/products"</span>)]
    <span style="background:#f2f19d;">[OutputCache(Duration = 60, VaryByParam = <span class="str">"none"</span>)]</span>
    <span class="key">public</span> IHttpActionResult GetProducts()
    {
        <span class="key">var</span> products = GetProductsFromDatabase();
        <span class="key">return</span> Ok(products);
    }
} </code></pre>

<ul class="ol1 ol1-mb-0">
<li class="custp1"><b>Duration:</b> Specifies how long the response should be cached, in seconds.</li>
<li><b>VaryByParam:</b> Specifies whether to vary the cached response based on query string parameters.</li>
</ul>

</div>
</div>



<li class="custp1"><strong>ETag header:</strong> It enables conditional caching to avoid sending unchanged data. If the resource hasn&#8217;t changed since the last request, the server can return a <strong>304 Not Modified</strong> status instead of sending the full response. 
</li>
<div> 
<button class="shbtnlist" id="shbtn94086" onclick="showHideBlock(94086)">▼ <u>Show example</u></button> 
<div id="shdiv94086" style="display: none;"> 
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ProductsController : ApiController
{
    [<span class="custkey">HttpGet</span>]
    [Route(<span class="str">"api/products/{id}"</span>)]
    <span class="key">public</span> IHttpActionResult GetProduct(<span class="key">int</span> id)
    {
        <span class="key">var</span> product = GetProductById(id);
        <span class="key">if</span> (product == <span class="key">null</span>)
        {
            <span class="key">return</span> NotFound();
        }

        <span class="key">var</span> etag = ComputeETag(product);
        <span class="key">if</span> (HttpContext.Current.Request.Headers[<span class="str">"If-None-Match"</span>] == etag)
        {
            <span class="key">return</span> StatusCode(HttpStatusCode.NotModified);
        }

        <span style="background:#f2f19d;">HttpContext.Current.Response.Headers[<span class="str">"ETag"</span>] = etag;</span>
        <span class="key">return</span> Ok(product);
    }

    <span class="key">private</span> <span class="key">string</span> ComputeETag(Product product)
    {
        <span class="com">// Simplified example: generate an ETag based on product properties</span>
        <span class="key">return</span> $<span class="str">"\"</span>{product.Id}-{product.LastModified.Ticks}\<span class="str">""</span>;
    }
} </code></pre>

</div> 
</div>



<li class="custp1"><strong>Response Caching Middleware:</strong> You can use the response caching middleware to enable caching.
</li>
<div>
<button class="shbtnlist" id="shbtn24139" onclick="showHideBlock(24139)">▼ <u>Show example</u></button>
<div id="shdiv24139" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.<span style="background:#f2f19d;">AddResponseCaching()</span>;
    }

    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.<span style="background:#f2f19d;">UseResponseCaching()</span>;

        app.UseRouting();
        app.UseEndpoints(endpoints =&gt;
        {
            endpoints.MapControllers();
        });
    }
}

<span class="com">// Controller Example</span>
[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    [<span class="custkey">HttpGet</span>]
    <span style="background:#f2f19d;">[ResponseCache(Duration = 60)]</span>
    <span class="key">public</span> IActionResult GetProducts()
    {
        <span class="key">var</span> products = GetProductsFromDatabase();
        <span class="key">return</span> Ok(products);
    }
} </code></pre>

</div>
</div>

</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you create a Custom Formatter in Web API?</strong></h3>



<p class="custp1 p-mb-0">Creating a <strong>Custom Formatter</strong> allows you to control how data is serialized and deserialized, enabling support for custom media types beyond the default JSON or XML. </p>



<p class="custp1 p-mb-0"><strong><em>Steps to Create a Custom Formatter:</em></strong></p>



<ol class="ol1 ol1-mb-0">
<li class="custp1"><strong>Create a Custom MediaTypeFormatter:</strong> Derive a class from <b>MediaTypeFormatter</b> or one of its built-in subclasses (<b>BufferedMediaTypeFormatter</b>, <b>JsonMediaTypeFormatter</b>, etc.) and implement the necessary methods for reading and writing content.
<div>
<button class="shbtnlist" id="shbtn52273" onclick="showHideBlock(52273)">&#9660; <u>Show example</u></button>
<div id="shdiv52273" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> CustomTextMediaTypeFormatter : MediaTypeFormatter
{
    <span class="key">public</span> CustomTextMediaTypeFormatter()
    {
        <span class="com">// Add the supported media type</span>
        SupportedMediaTypes.<b>Add</b>(<span class="key">new</span> MediaTypeHeaderValue(<span class="str" style="background:#f2f19d;">"text/custom"</span>));
    }

    <span class="com">// Override CanReadType to specify which types the formatter can deserialize</span>
    <span class="key">public</span> <span class="key">override</span> <span class="key">bool</span> CanReadType(Type type)
    {
        <span class="key">return</span> type == <span class="key">typeof</span>(<span class="key">string</span>);
    }

    <span class="com">// Override CanWriteType to specify which types the formatter can serialize</span>
    <span class="key">public</span> <span class="key">override</span> <span class="key">bool</span> CanWriteType(Type type)
    {
        <span class="key">return</span> type == <span class="key">typeof</span>(<span class="key">string</span>);
    }

    <span class="com">// Implement reading from the request body</span>
    <span class="key">public</span> <span class="key">override</span> <span class="key">async</span> Task&lt;<span class="key">object</span>&gt ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        <span class="key">using</span> (<span class="key">var</span> reader = <span class="key">new</span> StreamReader(readStream))
        {
            <span class="key">string</span> result = <span class="key">await</span> reader.ReadToEndAsync();
            <span class="key">return</span> result;
        }
    }

    <span class="com">// Implement writing to the response body</span>
    <span class="key">public</span> <span class="key">override</span> <span class="key">async</span> Task WriteToStreamAsync(Type type, <span class="key">object</span> value, Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        <span class="key">using</span> (<span class="key">var</span> writer = <span class="key">new</span> StreamWriter(writeStream))
        {
            <span class="key">await</span> writer.WriteAsync(value.ToString());
        }
    }
} </code></pre>

</div>
</div>
</li>



<li class="custp1"><strong>Register the Custom Formatter</strong> in the Startup.cs or Program.cs file.
<div>
<button class="shbtnlist" id="shbtn3300" onclick="showHideBlock(3300)">&#9660; <u>Show example</u></button>
<div id="shdiv3300" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
    {
        services.AddControllers(options =&gt
        {
            <span class="com">// Register the custom formatter</span>
            options.<span style="background:#f2f19d;">OutputFormatters.Add(<span class="key">new</span> CustomTextMediaTypeFormatter())</span>;
            options.<span style="background:#f2f19d;">InputFormatters.Add(<span class="key">new</span> CustomTextMediaTypeFormatter())</span>;
        });
    }

    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        <span class="com">// ....</span>
    }
} </code></pre>

</div>
</div>
</li>



<li class="custp1"><strong>Use the formatter</strong> in your controllers by specifying the media type it supports (<b>text/custom</b> in this case).
<div>
<button class="shbtnlist" id="shbtn62209" onclick="showHideBlock(62209)">&#9660; <u>Show example</u></button>
<div id="shdiv62209" style="display: none;">

<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> CustomFormatterController : ControllerBase
{
    [<span class="custkey">HttpGet</span>]
    <span style="background:#f2f19d;">[<b>Produces</b>(<span class="str">"text/custom"</span>)]</span>
    <span class="key">public</span> IActionResult Get()
    {
        <span class="key">return</span> Ok(<span class="str">"This is a custom formatted string"</span>);
    }

    [<span class="custkey">HttpPost</span>]
    <span style="background:#f2f19d;">[<b>Consumes</b>(<span class="str">"text/custom"</span>)]</span>
    <span class="key">public</span> IActionResult Post([FromBody] <span class="key">string</span> value)
    {
        <span class="key">return</span> Ok($<span class="str">"Received: {value}"</span>);
    }
} </code></pre>

</div>
</div>
</li>

</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Session State?</strong></h3>



<p class="custp1 p-mb-0">Session state is a server-side storage mechanism that retains user-specific data across multiple requests within a web application.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle Session State in Web API?</strong></h3>



<p class="custp1 p-mb-0">You can maintain Session State in a Web API by using techniques such as server-side storage, client-side tokens, or distributed caching. Below are some common approaches to handling session state:</p>



<p class="custp1 p-mb-0"><strong>1) Using In-Memory Caching:</strong> Suitable for simple scenarios <strong><em>with a single server</em></strong>.</p>



<button class="shbtn" id="shbtn56935" onclick="showHideBlock(56935)">&#9660; <u>Show example</u></button>
<div id="shdiv56935" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>a) Configure Memory Cache in Startup.cs file.</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
    {
        <span class="com">// Add memory cache services</span>
        services.<span style="background:#f2f19d;">AddMemoryCache()</span>;
        services.<span style="background:#f2f19d;">AddSession(options =&gt
        {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        })</span>;

        services.AddControllers();
    }

    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseHttpsRedirection();

        app.UseRouting();

        app.<span style="background:#f2f19d;">UseSession()</span>; <span class="com">// Enable session handling</span>

        <span class="com">// ....</span>
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Controller Example:</b></div>
<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> SessionController : ControllerBase
{
    [<span class="custkey">HttpGet</span>(<span class="str">"set"</span>)]
    <span class="key">public</span> IActionResult SetSession(<span class="key">string</span> key, <span class="key">string</span> value)
    {
        <span style="background:#f2f19d;">HttpContext.Session.SetString(key, value);</span>
        <span class="key">return</span> Ok(<span class="str">"Session value set"</span>);
    }

    [<span class="custkey">HttpGet</span>(<span class="str">"get"</span>)]
    <span class="key">public</span> IActionResult GetSession(<span class="key">string</span> key)
    {
        <span style="background:#f2f19d;"><span class="key">var</span> value = HttpContext.Session.GetString(key);</span>
        <span class="key">return</span> Ok(value ?? <span class="str">"Session value not found"</span>);
    }
} </code></pre>
</div>
<br><br>



<p class="p-mb-0"><strong>2) Distributed Session State:</strong> (Using Distributed Cache): Distributed cache is ideal for handling session state in environments where the API is <strong><em>hosted on multiple servers</em></strong> (e.g., in a cloud environment).</p>



<button class="shbtn" id="shbtn9982" onclick="showHideBlock(9982)">&#9660; <u>Show example</u></button>
<div id="shdiv9982" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
    {
        <span class="com">// Use Redis or SQL Server for distributed caching</span>
        services.<span style="background:#f2f19d;">AddStackExchangeRedisCache</span>(options =&gt
        {
            options.Configuration = <span class="str">"localhost:6379"</span>; <span class="com">// Redis server address</span>
            options.InstanceName = <span class="str">"SampleInstance"</span>;
        });

        services.AddSession(options =&gt
        {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });

        services.AddControllers();
    }

    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        <span class="com">// ....</span>

        app.<span style="background:#f2f19d;">UseSession()</span>; <span class="com">// Enable session handling</span>

        <span class="com">// ....</span>
    }
} </code></pre>

</div>
<br><br>



<p class="p-mb-0"><strong>3) Client-Side Token-Based Session Management:</strong> Uses JWT tokens to manage session state client-side. In token-based authentication, session data can be stored in a secure token (e.g., JWT &#8211; JSON Web Token) and sent with each request.</p>



<p class="custp1 p-mb-0"><strong><em>Steps:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Generate a token</strong> when the user logs in.</li>



<li><strong>Include the token</strong> in the Authorization header of each request.</li>



<li><strong>Validate the token</strong> on the server to retrieve the session data.</li>
</ul>



<button class="shbtn" id="shbtn80718" onclick="showHideBlock(80718)">&#9660; <u>Show example</u></button>
<div id="shdiv80718" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>a) Code Example for Generating JWT:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> TokenController : ControllerBase
{
    [<span class="custkey">HttpPost</span>(<span class="str">"token"</span>)]
    <span class="key">public</span> IActionResult GetToken([FromBody] UserLogin login)
    {
        <span class="key">if</span> (IsValidUser(login))
        {
            <span class="key">var</span> token = GenerateJwtToken(login);
            <span class="key">return</span> Ok(<span class="key">new</span> { token });
        }
        <span class="key">return</span> Unauthorized();
    }

    <span class="key">private</span> <span class="key">string</span> GenerateJwtToken(UserLogin login)
    {
        <span class="key">var</span> claims = new[]
        {
            <span class="key">new</span> Claim(JwtRegisteredClaimNames.Sub, login.Username),
            <span class="key">new</span> Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        <span class="key">var</span> key = <span class="key">new</span> SymmetricSecurityKey(Encoding.UTF8.GetBytes(<span class="str">"your_secret_key"</span>));
        <span class="key">var</span> creds = <span class="key">new</span> SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        <span class="key">var</span> <span style="background:#f2f19d;">token</span> = <span class="key">new</span> <span style="background:#f2f19d;">JwtSecurityToken</span>(
            issuer: <span class="str">"yourdomain.com"</span>,
            audience: <span class="str">"yourdomain.com"</span>,
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: creds);

        <span class="key">return</span> <span class="key">new</span> JwtSecurityTokenHandler().WriteToken(token);
    }

    <span class="key">private</span> <span class="key">bool</span> IsValidUser(UserLogin login)
    {
        <span class="com">// Validate the user credentials</span>
        <span class="key">return</span> true;
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>b) Controller Example:</b></div>
<pre class="pchl"><code>[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span style="background:#f2f19d;">[Authorize]</span> <span class="com">// Ensure token validation</span>
<span class="key">public</span> <span class="key">class</span> SecureDataController : ControllerBase
{
    [<span class="custkey">HttpGet</span>]
    <span class="key">public</span> IActionResult GetSecureData()
    {
        <span class="key">return</span> Ok(<span class="str">"This is secured data accessible via a valid token"</span>);
    }
} </code></pre>

</div>
<br><br>



<p class="p-mb-0"><strong>4) Using Cookies:</strong> Although not common in Web APIs, you can use cookies to store session data on the client-side. This method can be combined with server-side session storage or token-based authentication.</p>



<button class="shbtn" id="shbtn63293" onclick="showHideBlock(63293)">&#9660; <u>Show example</u></button>
<div id="shdiv63293" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> SessionController : ControllerBase
{
    [<span class="custkey">HttpGet</span>(<span class="str">"set"</span>)]
    <span class="key">public</span> IActionResult SetCookie(<span class="key">string</span> key, <span class="key">string</span> value)
    {
        CookieOptions option = <span class="key">new</span> <span style="background:#f2f19d;">CookieOptions</span>
        {
            Expires = DateTime.Now.AddMinutes(30)
        };
        <span style="background:#f2f19d;">Response.Cookies.Append(key, value, option)</span>;
        <span class="key">return</span> Ok(<span class="str">"Cookie value set"</span>);
    }

    [<span class="custkey">HttpGet</span>(<span class="str">"get"</span>)]
    <span class="key">public</span> IActionResult GetCookie(<span class="key">string</span> key)
    {
        <span class="key">var</span> value = <span style="background:#f2f19d;">Request.Cookies[key]</span>;
        <span class="key">return</span> Ok(value ?? <span class="str">"Cookie value not found"</span>);
    }
} </code></pre>

</div>
<br><br>



<p class="p-mb-0">Each method has its use case depending on the application&#8217;s architecture, scalability, and security requirements.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement HTTP method overrides in Web API?</strong></h3>



<p class="custp1 p-mb-0">HTTP method overrides are used to allow clients to &#8220;override&#8221; the HTTP method of a request, typically when the client is limited to using certain HTTP methods like POST but needs to perform other operations like PUT. This is commonly achieved by using a special HTTP header <span class="spanHT">X-HTTP-Method-Override</span>.</p>



<button class="shbtn" id="shbtn35440" onclick="showHideBlock(35440)">&#9660; <u>Show example</u></button>
<div id="shdiv35440" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><h3><b>Steps to Implement HTTP Method Overrides:</b></h3>
<br> <b>1) Enable the Middleware:</b> You need to add the HttpMethodOverride Middleware to your request pipeline in the Startup.cs file.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        <span class="com">// Enable the HTTP Method Override middleware</span>
        app.<span style="background:#f2f19d;">UseHttpMethodOverride()</span>;
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2) Using the Method Override:</b> The middleware allows the client to specify the intended HTTP method through the &#39;X-HTTP-Method-Override&#39; header. For example, if the client can only make POST requests but needs to perform a PUT operation, it can include the &#39;X-HTTP-Method-Override&#39; header in the request.
</div>
<pre class="pchl"><code><b>POST</b> /api/products/1 HTTP/1.1
Host: example.com
<span style="background:#f2f19d;">X-HTTP-Method-Override</span>: <b>PUT</b>
Content-Type: application/json

{
    <span class="str">"name"</span>: <span class="str">"Updated Product Name"</span>
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is form-data?</strong></h3>



<p class="custp1 p-mb-0"><strong>Form-data</strong> is a format used to send key-value pairs, including files, from a client (like a web browser) to a server, typically in an HTTP POST request. It&#8217;s commonly used for submitting forms that include file uploads.</p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Different between <strong>IFormFile</strong> and <strong>[FormForm]</strong>.</strong></h3>



<p class="custp1 p-mb-0"><strong><strong><strong>IFormFile</strong> and <strong>[FormForm]</strong></strong></strong> are often used when a client sends a file or data using &#8216;multipart/form-data&#8217; content type POST request, which is typically used when submitting forms with files or mixed data (multipart file uploads). Here are the differences:</p>



<br>
<table>
    <thead>
        <tr>
            <th>IFormFile</th>
            <th>[FromForm]</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Represents a file sent with the HTTP request.</td>
            <td>Specifies that a parameter should be bound from form data.</td>
        </tr>
        <tr>
            <td>Interface Type</td>
            <td>Attribute Type</td>
        </tr>
        <tr>
            <td>Used specifically for handling uploaded files.</td>
            <td>Used to bind entire models or individual parameters.</td>
        </tr>
        <tr>
            <td>Accessing file content and metadata in file upload scenarios.</td>
            <td>Binding form data in multipart/form-data requests.</td>
        </tr>
        <tr>
            <td>Focused only on handling individual file uploads.</td>
            <td>Can be applied to complex objects containing multiple fields, including files.</td>
        </tr>
        <tr>
            <td><i>syntax:</i><br><pre class="pchl" style="margin-top: 7px;"><code>[HttpPost(<span class="str">"uploadfile"</span>)]
<span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt UploadFile(IFormFile file)
{
} </code></pre></td>
            <td><i>syntax:</i><br><pre class="pchl" style="margin-top: 7px;"><code>[HttpPost(<span class="str">"uploadfiles"</span>)]
<span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt UploadFiles([FromForm] UploadModel model)
{
} </code></pre></td>
        </tr>
    </tbody>
</table>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you upload and download <strong>file</strong></strong>s<strong> in a Web API?</strong></h3>



<br>



<p class="p-mb-0"><strong>1) File Uploading: </strong>Use <span class="spanHT">IFormFile</span> or <span class="spanHT">[FromForm]</span> as an action method parameter to upload files and store them on the server using a FileStream.</p>



<p class="custp1 p-mb-0 p-lp-15"><strong>a. Using IFormFile Interface:</strong> <span class="spanHT">IFormFile</span> handles file uploads from the HTTP request and provides a way to access the uploaded file&#8217;s metadata (like file name and content type). For multiple file uploads use <span class="spanHT">List&lt;IFormFile&gt;</span></p>



<div class="p-lp-15">
<button class="shbtn" id="shbtn43294" onclick="showHideBlock(43294)">&#9660; <u>Show example</u></button>
<div id="shdiv43294" style="display: none;">

<pre class="pchl"><code>[HttpPost(<span class="str">"upload"</span>)]
<span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt UploadFile(<span style="background:#f2f19d;">IFormFile</span> file)
{
	<span class="key">if</span> (file != <span class="key">null</span> && file.Length &gt 0)
	{
		<span class="key">var</span> filePath = Path.Combine(<span class="str">"uploads"</span>, file.FileName);

		<span class="com">// Ensure the directory exists</span>
		<span class="key">if</span> (!Directory.Exists(<span class="str">"uploads"</span>))
		{
			Directory.CreateDirectory(<span class="str">"uploads"</span>);
		}

		<span class="key">using</span> (<span class="key">var</span> stream = <span class="key">new</span> FileStream(filePath, FileMode.Create))
		{
			<span class="key">await</span> <span style="background:#f2f19d;">file.CopyToAsync(stream)</span>;
		}

		<span class="key">return</span> Ok(<span class="key">new</span> { message = <span class="str">"File uploaded successfully!"</span> });
	}

	<span class="key">return</span> BadRequest(<span class="str">"File is required."</span>);
} </code></pre>

</div>
</div>



<p class="custp1 p-mb-0 p-lp-15"><strong>b. Using [FromForm] attribute:</strong> <span class="spanHT">[FromForm]</span> binds form data (fields &amp; file uploads) to action method parameters. <span class="spanHT">IFormFile</span> is used in conjunction with <span class="spanHT">[FromForm]</span> to handle file uploads along with other form data.</p>



<div class="p-lp-15">
<button class="shbtn" id="shbtn12416" onclick="showHideBlock(12416)">&#9660; <u>Show example</u></button>
<div id="shdiv12416" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Uploading multiple files to Azure Blob Storage &#8211; Example</b>
<br><br> <b>1)</b> Create model class with fields and file properties.
</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <b>UploadModel</b>
{
    <span class="com">// multiple file upload</span>
    <span class="key">public</span> <span class="custkey">List</span>&lt;<span style="background:#f2f19d;">IFormFile</span>&gt Files { get; set; }

    <span class="key">public</span> <span class="key">string</span> ProductCode { set; get; }
} </code></pre>



<br><br>
<div style="padding-left: 0.3125rem;"><b>2) File Upload Action Method (API)</b></div>
<pre class="pchl"><code>[HttpPost(<span class="str">"uploadfiles"</span>)]
<span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt UploadFiles(<span style="background:#f2f19d;">[FromForm]</span> <b>UploadModel</b> model)
{
	<span class="key">if</span> (CloudStorageAccount.TryParse(config.Value.StorageConnection, <span class="key">out</span> CloudStorageAccount storageAccount))
	{
		CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
		CloudBlobContainer container = blobClient.GetContainerReference(config.Value.Container);
		<span class="key">await</span> container.CreateIfNotExistsAsync();

		CloudBlobDirectory recipefolder = container.GetDirectoryReference(<span class="str">"Recipe"</span>);
		<span class="key">await</span> recipefolder.Container.CreateIfNotExistsAsync();
		
		<span style="background:#f2f19d;"><span class="custkey">List</span>&lt;IFormFile&gt files = model.Files;</span>
		
		<span class="custkey">Parallel</span>.ForEach(<span style="background:#f2f19d;">files</span>, <span style="background:#f2f19d;">file</span> =&gt
		{
			CloudBlockBlob blob = recipefolder.GetBlockBlobReference(file.FileName);
			blob.UploadFromStreamAsync(<span style="background:#f2f19d;">file.OpenReadStream()</span>);
		});

	}
} </code></pre>

</div>
</div>
<br>



<p class="p-mb-0"><strong>2) File Downloading: </strong></p>



<p class="p-mb-0 p-lp-15">To allow clients to download a file, read the file from the server using <span class="spanHT">FileStream</span> and use the base <span class="spanHT">File()</span> method to return a file stream as an <span class="spanHT">IActionResult</span> with the appropriate content type.</p>



<div class="p-lp-15">
<button class="shbtn" id="shbtn1346" onclick="showHideBlock(1346)">&#9660; <u>Show example</u></button>
<div id="shdiv1346" style="display: none;" class="shdt">

<pre class="pchl"><code>[HttpGet(<span class="str">"download/{fileName}"</span>)]
<span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt DownloadFile(<span class="key">string</span> fileName)
{
    <span class="key">var</span> filePath = Path.Combine(<span class="str">"uploads"</span>, fileName);

    <span class="key">if</span> (!System.IO.File.Exists(filePath))
    {
        <span class="key">return</span> NotFound(<span class="key">new</span> { message = <span class="str">"File not found."</span> });
    }

    <span class="key">var</span> memory = <span class="key">new</span> MemoryStream();
    <span class="key">using</span> (<span class="key">var</span> stream = <span class="key">new</span> FileStream(filePath, FileMode.Open))
    {
        <span class="key">await</span> stream.CopyToAsync(memory);
    }
    memory.Position = 0;

    <span class="key">return</span> <span style="background:#f2f19d;"><b>File</b>(memory, GetContentType(filePath), Path.GetFileName(filePath))</span>;
	

    <span class="com">// <b>To download file from Azure Blob Storage</b></span>
    <span class="com">// CloudBlob file = recipefolder.GetBlobReference(recipe.Recipe_Name);</span>
    <span class="com">// if (await file.ExistsAsync())</span>
    <span class="com">// {</span>
    <span class="com">//    await file.DownloadToStreamAsync(ms);</span>
    <span class="com">//    Stream blobStream = file.OpenReadAsync().Result;</span>
    <span class="com">//    return <span style="background:#f2f19d;"><b>File</b>(blobStream, file.Properties.ContentType, file.Name)</span>;</span>
    <span class="com">// }</span>
}


<span class="key">private</span> <span class="key">string</span> GetContentType(<span class="key">string</span> path)
{
    <span class="key">var</span> types = <span class="key">new</span> Dictionary&lt;<span class="key">string</span>, <span class="key">string</span>&gt
    {
        {<span class="str">".txt"</span>, <span class="str">"text/plain"</span>},
        {<span class="str">".pdf"</span>, <span class="str">"application/pdf"</span>},
        {<span class="str">".doc"</span>, <span class="str">"application/vnd.ms-word"</span>},
        {<span class="str">".docx"</span>, <span class="str">"application/vnd.ms-word"</span>},
        {<span class="str">".xls"</span>, <span class="str">"application/vnd.ms-excel"</span>},
        {<span class="str">".xlsx"</span>, <span class="str">"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"</span>},
        {<span class="str">".png"</span>, <span class="str">"image/png"</span>},
        {<span class="str">".jpg"</span>, <span class="str">"image/jpeg"</span>},
        {<span class="str">".jpeg"</span>, <span class="str">"image/jpeg"</span>},
        {<span class="str">".gif"</span>, <span class="str">"image/gif"</span>},
        {<span class="str">".csv"</span>, <span class="str">"text/csv"</span>}
    };

    <span class="key">var</span> ext = Path.GetExtension(path).ToLowerInvariant();
    <span class="key">return</span> types.ContainsKey(ext) ? types[ext] : <span class="str">"application/octet-stream"</span>;
} </code></pre>

</div>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you Encode and Decode a <strong>URL</strong> or text?</strong></h3>



<p class="custp1 p-mb-0">Handling URL encoding and decoding ensures that special characters in the URL or text are properly processed. You can use <span class="spanHT">System.Net.WebUtility</span> or <span class="spanHT">System.Uri</span> classes.</p>



<p class="custp1 p-mb-0"><strong>1) URL Encoding:</strong> Converts special characters in a URL or text into a format that can be transmitted over the Internet. For example, <em>spaces</em> are replaced with <em>%20</em>. </p>



<button class="shbtn" id="shbtn83126" onclick="showHideBlock(83126)">&#9660; <u>Show example</u></button>
<div id="shdiv83126" style="display: none;">

<pre class="pchl"><code><span class="key">string</span> encodedUrl = WebUtility.<span style="background:#f2f19d;">UrlEncode</span>(<span class="str">"https://example.com/search?query=hello world"</span>);

<span class="com">// Output: https%3A%2F%2Fexample.com%2Fsearch%3Fquery%3Dhello%20world</span></code></pre>

</div>
<br><br>



<p class="p-mb-0"><strong>2) URL Decoding:</strong> Reverts the encoded URL back to its original form, making it readable and usable in the application. </p>



<button class="shbtn" id="shbtn96487" onclick="showHideBlock(96487)">&#9660; <u>Show example</u></button>
<div id="shdiv96487" style="display: none;">

<pre class="pchl"><code><span class="key">string</span> decodedUrl = WebUtility.<span style="background:#f2f19d;">UrlDecode</span>(<span class="str">"https%3A%2F%2Fexample.com%2Fsearch%3Fquery%3Dhello%20world"</span>);

<span class="com">// Output: https://example.com/search?query=hello world</span></code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between Transient, Scoped, and Singleton services in Web API?</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th>Service Lifetime</th>
            <th>Description</th>
            <th>Use Case Example</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Transient</th>
            <td>A new instance of the service is created each time it is requested. (Per request)</td>
            <td>Use for lightweight, stateless services where a new instance is needed for each operation.</td>
        </tr>
        <tr>
            <th>Scoped</th>
            <td>A new instance of the service is created once per request or scope. (Per web request)</td>
            <td>Use for services that need to maintain state within a single request but not across different requests, such as database context classes.</td>
        </tr>
        <tr>
            <th>Singleton</th>
            <td>A single instance of the service is created and shared throughout the application&#39;s lifetime. (Entire application)</td>
            <td>Use for services that maintain state globally across the entire application, such as configuration settings or logging services.</td>
        </tr>
    </tbody>
</table>



<button class="shbtn" id="shbtn45575" onclick="showHideBlock(45575)">&#9660; <u>Show example</u></button>
<div id="shdiv45575" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Example of Registering Services</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
{
    services.<span style="background:#f2f19d;">AddTransient</span>&lt;ITransientService, TransientService&gt();
    services.<span style="background:#f2f19d;">AddScoped</span>&lt;IScopedService, ScopedService&gt();
    services.<span style="background:#f2f19d;">AddSingleton</span>&lt;ISingletonService, SingletonService&gt();
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is API rate limiting and how can it be implemented in Web API applications?</strong></h3>



<p class="custp1 p-mb-0"><strong>API rate limiting</strong> is a technique used to control the number of requests a client can make to an API within a specified time period. This helps prevent abuse, ensures fair usage, and protects the API from getting overloaded with too many requests. Rate limiting can be crucial for maintaining the performance, reliability, and security of an API. You can implement rate limiting using custom middleware.</p>



<button class="shbtn" id="shbtn4741" onclick="showHideBlock(4741)">&#9660; <u>Show example</u></button>
<div id="shdiv4741" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1) Create custom middleware</b> to track and limit the number of requests from each client.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> RateLimitingMiddleware
{
    <span class="key">private</span> <span class="key">readonly</span> RequestDelegate _next;
    <span class="key">private</span> <span class="key">static</span> <span class="key">readonly</span> Dictionary&lt;<span class="key">string</span>, <span class="key">int</span>&gt ClientRequestCounts = <span class="key">new</span> Dictionary&lt;<span class="key">string</span>, <span class="key">int</span>&gt();
    <span class="key">private</span> <span class="key">static</span> <span class="key">readonly</span> TimeSpan TimeWindow = TimeSpan.FromMinutes(1);
    <span class="key">private</span> <span class="key">const</span> <span class="key">int</span> <b>MaxRequestsPerWindow</b> = 10;

    <span class="key">public</span> RateLimitingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    <span class="key">public</span> <span class="key">async</span> Task InvokeAsync(HttpContext context)
    {
        <span class="key">var</span> clientIp = context.Connection.RemoteIpAddress?.ToString();

        <span class="key">if</span> (clientIp != <span class="key">null</span>)
        {
            <span class="key">if</span> (ClientRequestCounts.ContainsKey(clientIp))
            {
                ClientRequestCounts[clientIp]++;
            }
            <span class="key">else</span>
            {
                ClientRequestCounts[clientIp] = 1;
            }

            <span class="key">if</span> (ClientRequestCounts[clientIp] &gt <b>MaxRequestsPerWindow</b>)
            {
                context.Response.StatusCode = 429; <span class="com">// Too Many Requests</span>
                <span class="key">await</span> context.Response.WriteAsync(<span class="str">"Rate limit exceeded. Try again later."</span>);
                return;
            }
        }

        <span class="key">await</span> _next(context);
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2) Register the Middleware</b> in Statup.cs file.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMiddleware&lt;<span style="background:#f2f19d;">RateLimitingMiddleware</span>&gt();

    <span class="com">// ....</span>
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you ensure backward compatibility when updating a Web API?</strong></h3>



<p class="custp1 p-mb-0">To ensure backward compatibility when updating a Web API, follow these practices:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Versioning the API:</strong> Introduce new versions of your API rather than changing existing endpoints. Use versioning strategies like URL versioning (e.g., /api/v2/resource), query string parameters (e.g., /api/resource?version=2), or custom headers (e.g., api-version: 2.0).</li>



<li><strong>Deprecate Endpoints Gradually:</strong> Inform users in advance about deprecated endpoints or features. Provide a transition period where both the old and new versions are available.</li>



<li><strong>Add New Endpoints Instead of Modifying Existing Ones:</strong> Add new functionality through new endpoints rather than modifying the behavior of existing ones.</li>



<li><strong>Maintain Schema Compatibility:</strong> Ensure that changes to data structures (like adding new fields) are backward-compatible. Avoid removing or renaming existing fields in responses.</li>



<li><strong>Use Default Values for New Fields:</strong> When adding new fields to API responses or requests, provide default values so that old clients can continue working without changes.</li>



<li><strong>Contract Testing:</strong> Use contract tests to ensure that changes in the API do not break existing clients.</li>



<li><strong>Document Changes Clearly:</strong> Update the API documentation to reflect the changes, specifying the differences between versions and the impact on clients.</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is DTO (Data Transfer Objects)? How do you create and use DTOs in Web API?</strong></h3>



<p class="custp1 p-mb-0"><strong>DTO (Data Transfer Objects)</strong> is a simple object that ensures only necessary data is transferred across different layers of an application, particularly between the client and server in a Web API. DTOs typically contain only the data needed by the client, excluding any unnecessary or sensitive information. </p>



<p class="custp1 p-mb-0"><strong>1) Creating DTOs:</strong> Let&#8217;s say you have a <strong>Product entity</strong> class with several properties and it exposes some internal &amp; sensitive information, as shown in the example: </p>



<button class="shbtn" id="shbtn89930" onclick="showHideBlock(89930)">&#9660; <u>Show example</u></button>
<div id="shdiv89930" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Product
{
    <span class="key">public</span> <span class="key">int</span> Id { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> <span class="key">decimal</span> Price { get; set; }
    <span class="key">public</span> DateTime CreatedDate { get; set; }  <span style="color:red;">// Internal information</span>
    <span class="key">public</span> <span class="key">string</span> InternalCode { get; set; }  <span style="color:red;">// Sensitive information</span>
} </code></pre>

</div>



<p class="custp1 p-mb-0"><strong>2)</strong> You can create a <strong>ProductDTO</strong> to show only the necessary fields required &amp; applicable to the client, as shown in the example:</p>



<button class="shbtn" id="shbtn73002" onclick="showHideBlock(73002)">&#9660; <u>Show example</u></button>
<div id="shdiv73002" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> ProductDTO
{
    <span class="key">public</span> <span class="key">int</span> Id { get; set; }
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> <span class="key">decimal</span> Price { get; set; }
} </code></pre>

</div>



<p class="custp1 p-mb-0"><strong>3) Using DTOs in Web API:</strong> Once you have created DTO, you can use it in your Web API actions to ensure that only the required data is sent to or received from the client, as shown in the example:</p>



<button class="shbtn" id="shbtn89122" onclick="showHideBlock(89122)">&#9660; <u>Show example</u></button>
<div id="shdiv89122" style="display: none;">

<pre class="pchl"><code><span class="com">// Sample Web API Controller</span>
[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> ProductsController : ControllerBase
{
    <span class="com">// Suppose you have a method to get a product by Id</span>
    [<span class="custkey">HttpGet</span>(<span class="str">"{id}"</span>)]
    <span class="key">public</span> ActionResult&lt;<span style="background:#f2f19d;">ProductDTO</span>&gt GetProduct(<span class="key">int</span> id)
    {
        <span class="com">// Fetch the product from the database</span>
		<span class="key">var</span> <b>productDTO</b> =_context.TProduct  
							.Where(p =&gt p.Id == Id)

							<span class="com">// Convert the Product to ProductDTO before returning it</span>
							.Select(s =&gt <span style="background:#f2f19d;"><span class="key">new</span> ProductDTO
							{
								Id = s.Id,
								Name = s.Name,
								Price = s.Price
							}</span>);

        <span class="key">return</span> Ok(</b>productDTO</b>);
    }

    <span class="com">// A method to create a new product using a DTO</span>
    [<span class="custkey">HttpPost</span>]
    <span class="key">public</span> IActionResult CreateProduct(<span style="background:#f2f19d;">ProductDTO <b>productDTO</b></span>)
    {
        <span class="com">// Convert the DTO to the Product entity</span>
        <span class="key">var</span> product = <span class="key">new</span> Product
        {
            Id = <span class="key">new</span> Random().Next(1, 1000),  <span class="com">// Just for example</span>
            Name = <b>productDTO</b>.Name,
            Price = <b>productDTO</b>.Price,
            CreatedDate = DateTime.UtcNow,
            InternalCode = <span class="str">"DEF456"</span>  <span class="com">// Example of internal code generation</span>
        };

        <span class="com">// Save the product to the database (code omitted)</span>
        
        <span class="key">return</span> CreatedAtAction(nameof(GetProduct), <span class="key">new</span> { id = product.Id }, productDTO);
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement API response compression in Web API?</strong></h3>



<p class="custp1 p-mb-0">Implementing API response compression in a Web API can significantly reduce the size of the data sent over the network, leading to faster response times and reduced bandwidth usage. .NET Core provides built-in middleware for response compression, which can be added to your application in the Startup.cs file. <strong>Gzip and Brotli</strong> are commonly used compression algorithms supported by .NET Core. Here’s how you can implement response compression in a .NET Core Web API: </p>



<p class="custp1 p-mb-0"><strong>1) Install the Required Package:</strong> If it&#8217;s not already included in your project, you may need to install <span class="spanHT">Microsoft.AspNetCore.ResponseCompression</span> package. </p>



<button class="shbtn" id="shbtn51260" onclick="showHideBlock(51260)">&#9660; <u>Show example</u></button>
<div id="shdiv51260" style="display: none;" class="shdt">
<br>
<div><b>Package Manager Console &#8211; command:</b></div>
<div style="padding:0.3125rem 0.625rem; color:#ffffff; background:#000000; margin-top: 0.3125rem;">dotnet add package Microsoft.AspNetCore.ResponseCompression
</div>
</div>
<br><br>



<p class="p-mb-0"><strong>2) Configure Response Compression in Startup.cs:</strong></p>



<p class="custp1 p-mb-0 p-lp-15"><strong>2.a)</strong> In the <strong>ConfigureServices</strong> method, add and configure the response compression middleware.</p>



<div class="p-lp-15">
<button class="shbtn" id="shbtn96988" onclick="showHideBlock(96988)">&#9660; <u>Show example</u></button>
<div id="shdiv96988" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    <span class="com">// Add response compression services</span>
    services.AddResponseCompression(options =&gt
    {
        options.EnableForHttps = true; <span class="com">// Enable compression even for HTTPS requests</span>
        options.Providers.Add&lt;<b>GzipCompressionProvider</b>&gt(); <span class="com">// Add GZIP compression</span>
        options.Providers.Add&lt;<b>BrotliCompressionProvider&gt</b>(); <span class="com">// Add Brotli compression</span>
    });

    <span class="com">// Optional: Configure the compression level (e.g., optimal, fast, etc.)</span>
    services.Configure&lt;<b>BrotliCompressionProviderOptions</b>&gt(options =&gt
    {
        options.Level = System.IO.Compression.CompressionLevel.Fastest;
    });

    services.Configure&lt;<b>GzipCompressionProviderOptions</b>&gt(options =&gt
    {
        options.Level = System.IO.Compression.CompressionLevel.Optimal;
        <span class="com">// <b>or</b> </span>
        <span class="com">// options.Level = System.IO.Compression.CompressionLevel.SmallestSize; </span>
    });
} </code></pre>

</div>
</div>



<p class="custp1 p-mb-0 p-lp-15"><strong>2.b)</strong> In the <strong>Configure method</strong>, add the <strong>UseResponseCompression</strong> middleware to the request pipeline. </p>



<div class="p-lp-15">
<button class="shbtn" id="shbtn83121" onclick="showHideBlock(83121)">&#9660; <u>Show example</u></button>
<div id="shdiv83121" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    <span class="com">// ....</span>

    app.UseHttpsRedirection();

    <span class="com">// Add response compression to the pipeline</span>
    <span style="background:#f2f19d;">app.UseResponseCompression();</span>

    app.UseRouting();

    <span class="com">// ....</span>
} </code></pre>

</div>
</div>
<br>



<p class="p-mb-0"><strong>3) Verify Compression in a Response:</strong> Once configured, the Web API will automatically compress responses based on the client&#8217;s <span class="spanHT">Accept-Encoding</span> header. Clients that support compression will receive compressed responses (e.g., gzip or brotli), while others will receive uncompressed data. </p>



<p class="custp1 p-mb-0">When you make a request to your Web API, you can verify that compression is working by checking the Content-Encoding header in the response. </p>



<div style="padding:5px 10px; background:#000000; margin-top: 0.625rem; margin-bottom: 5px;"><span style="color:#ffffff;">curl -H</span> <span style="color:#00a67d; font-weight: 500;">&#8220;Accept-Encoding: gzip&#8221;</span> <span style="color:#ffffff;">https://yourapi.com/api/values</span>
</div>



<p class="custp1 p-mb-0">If compression is applied, you should see a <span class="spanHT">Content-Encoding: gzip</span> header in the response. </p>



<br>
<div class="note">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Note:</div>
<div>
<ul class="ol1-mb-0">
<li class="custp1"><b>Compression Levels</b> can be adjusted to balance between CPU usage and compression ratio.</li>
<li><b>HTTPS Compression</b> can be enabled, though it should be used with caution due to potential security considerations.</li>
</ul>
</div>
</div>



<p><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"><em>read more:</em></mark> <a href="https://learn.microsoft.com/en-us/aspnet/core/performance/response-compression?view=aspnetcore-8.0" target="_blank" rel="noreferrer noopener">Response compression (learn.microsoft.com)</a></p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you manage environment-specific configurations in Web API?</strong></h3>



<p class="custp1 p-mb-0">Managing environment-specific configurations ensures the application behaves correctly in different environments, such as Development, Staging, and Production. Here are some basic steps:</p>



<ul class="ol1 ol1-mb-0">

<li class="custp1"><strong>Use appsettings.json Files:</strong> ASP.NET Core uses <b>appsettings.json</b> to store configuration settings. You can create different versions of this file for each environment:
<ul class="ol1 ol1-mb-0">
<li><strong>appsettings.json:</strong> Base configuration file.</li>
<li><strong>appsettings.Development.json:</strong> Configuration specific to the Development environment.</li>
<li><strong>appsettings.Staging.json:</strong> Configuration specific to the Staging environment.</li>
<li><strong>appsettings.Production.json:</strong> Configuration specific to the Production environment.</li>
</ul>
</li>


<li class="custp1"><strong>Load Environment-Specific Settings:</strong> ASP.NET Core automatically loads the appropriate <b>appsettings</b> file based on the current environment. The environment is specified by the <b>ASPNETCORE_ENVIRONMENT</b> environment variable.
<div>
<button class="shbtnlist" id="shbtn59480" onclick="showHideBlock(59480)">&#9660; <u>Show example</u></button>
<div id="shdiv59480" style="display: none;">

<pre class="pchl"><code><span class="key">using</span> Microsoft.Extensions.Configuration;

<span class="key">var</span> builder = WebApplication.CreateBuilder(args);

<span class="com">// Load base appsettings.json</span>
builder.Configuration
    .AddJsonFile(<span class="str">"appsettings.json"</span>, optional: <span class="key">false</span>, reloadOnChange: <span class="key">true</span>)
    <span class="com">// Load environment-specific appsettings.{EnvironmentName}.json</span>
    .AddJsonFile($<span class="str">"appsettings.{builder.Environment.EnvironmentName}.json"</span>, optional: <span class="key">true</span>, reloadOnChange: <span class="key">true</span>)
    <span class="com">// Optionally load settings from environment variables</span>
    .AddEnvironmentVariables();

<span class="key">var</span> app = builder.Build();

<span class="com">// Example: Use the configuration</span>
<span class="key">var</span> connectionString = builder.Configuration.GetConnectionString(<span class="str">"DefaultConnection"</span>);
Console.WriteLine($<span class="str">"Connection String: {connectionString}"</span>);

app.Run(); </code></pre>

</div>
</div>
</li>


<li class="custp1"><strong>Use Environment Variables:</strong> You can override settings in the appsettings.json files with environment variables. This is particularly useful for secrets like connection strings.
<div>
<button class="shbtnlist" id="shbtn92948" onclick="showHideBlock(92948)">&#9660; <u>Show example</u></button>
<div id="shdiv92948" style="display: none;">

<pre class="pchl"><code>ASPNETCORE_ENVIRONMENT=Production
ConnectionStrings__DefaultConnection=Server=myprodserver;Database=MyAppDbProd;User Id=myusername;Password=mypassword; </code></pre>

</div>
</div>
</li>

</ul>
<br>



<p><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"><em>read more:</em></mark> <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-8.0" target="_blank" rel="noreferrer noopener">Use multiple environments (learn.microsoft.com)</a></p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement request and response logging?</strong></h3>



<p class="custp1 p-mb-0">Middleware allows you to intercept and log the HTTP requests and responses as they pass through the pipeline. The logs will include information such as the HTTP method, the URL, and the response status code. The example shows:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>Creating a Custom Middleware for Logging.</li>



<li>During logging, the response body is temporarily copied to a MemoryStream to allow logging without affecting the original response stream.</li>



<li>Registering the Middleware.</li>



<li>Example Output.</li>
</ul>



<button class="shbtn" id="shbtn78740" onclick="showHideBlock(78740)">&#9660; <u>Show example</u></button>
<div id="shdiv78740" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Create a Custom Middleware for Logging.</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> RequestResponseLoggingMiddleware
{
    <span class="key">private</span> <span class="key">readonly</span> RequestDelegate _next;
    <span class="key">private</span> <span class="key">readonly</span> ILogger&lt;RequestResponseLoggingMiddleware&gt _logger;

    <span class="key">public</span> RequestResponseLoggingMiddleware(RequestDelegate next, ILogger&lt;RequestResponseLoggingMiddleware&gt logger)
    {
        _next = next;
        _logger = logger;
    }

    <span class="key">public</span> <span class="key">async</span> Task InvokeAsync(HttpContext context)
    {
        <span class="com">// <b>Log Request</b></span>
        <span style="background:#f2f19d;">_logger.LogInformation</span>(<span class="str">"Handling request: {method} {url}"</span>, context.Request.Method, context.Request.Path);

        <span class="com">// Copy original response body stream</span>
        <span class="key">var</span> originalBodyStream = context.Response.Body;

        <span class="key">using</span> (<span class="key">var</span> responseBody = <span class="key">new</span> <b>MemoryStream()</b>)
        {
            context.Response.Body = responseBody;

            <span class="key">await</span> _next(context); <span class="com">// Call the next middleware in the pipeline</span>

            <span class="com">// <b>Log Response</b></span>
            <span style="background:#f2f19d;">_logger.LogInformation</span>(<span class="str">"Response: {statusCode}"</span>, context.Response.StatusCode);

            <span class="key">await</span> responseBody.CopyToAsync(originalBodyStream);
        }
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Register the Middleware</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
	<span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
	{
		<span class="com">// ....</span>
		services.<span style="background:#f2f19d;">AddLogging()</span>;
		<span class="com">// ....</span>
	}

	<span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		<span class="com">// ....</span>
		app.<span style="background:#f2f19d;">UseMiddleware&lt;RequestResponseLoggingMiddleware&gt()</span>;
		<span class="com">// ....</span>
	}
} </code></pre>



<br><br><br>
<div style="padding-left: 0.3125rem;"><b>Example Output</b>
<br>When you make a request to your API, the logs might look like this:
</div>
<pre class="pchl"><code><span style="color: #df3079;">info:</span> <span style="color: #00a67d;">RequestResponseLoggingMiddleware[0]</span>
      <span style="color: #df3079;">Handling request:</span> <span style="color: #00a67d;">GET /api/values</span>
<span style="color: #df3079;">info:</span> <span style="color: #00a67d;">RequestResponseLoggingMiddleware[0]</span>
      <span style="color: #df3079;">Response: 200</span> </code></pre>



</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use ApiExplorer to generate metadata about Web API endpoints?</strong></h3>



<p class="custp1 p-mb-0"><span class="spanHT">ApiExplorer</span> is a feature in ASP.NET Core that provides metadata about your Web API endpoints, such as route information, HTTP methods, and parameter details. This metadata can be used for various purposes, including generating API documentation with tools like Swagger. By default, <strong>ApiExplorer</strong> is enabled for controllers in an ASP.NET Core. </p>



<p class="custp1 p-mb-0">You can access the ApiExplorer metadata programmatically through dependency injection using the <strong>IApiDescriptionGroupCollectionProvider</strong> interface, which provides a collection of <strong>ApiDescriptionGroup</strong>, where each group contains metadata about the API controllers and their actions. <strong>ApiDescription</strong> represents a single API endpoint, including details like the HTTP method, route, and parameters. Here&#8217;s an example of how to access it within a controller:</p>



<button class="shbtn" id="shbtn28662" onclick="showHideBlock(28662)">&#9660; <u>Show example</u></button>
<div id="shdiv28662" style="display: none;" class="shdt">

<pre class="pchl"><code><span class="key">using</span> Microsoft.AspNetCore.Mvc;
<span class="key">using</span> Microsoft.AspNetCore.Mvc.ApiExplorer;

[ApiController]
[Route(<span class="str">"api/[controller]"</span>)]
<span class="key">public</span> <span class="key">class</span> MetadataController : ControllerBase
{
    <span class="key">private</span> <span class="key">readonly</span> <span style="background:#f2f19d;">IApiDescriptionGroupCollectionProvider</span> _apiDescriptionGroupCollectionProvider;

    <span class="key">public</span> MetadataController(<span style="background:#f2f19d;">IApiDescriptionGroupCollectionProvider</span> apiDescriptionGroupCollectionProvider)
    {
        _apiDescriptionGroupCollectionProvider = apiDescriptionGroupCollectionProvider;
    }

    [<span class="custkey">HttpGet</span>(<span class="str">"endpoints"</span>)]
    <span class="key">public</span> IActionResult GetApiEndpoints()
    {
        <span class="key">var</span> apiDescriptions = _apiDescriptionGroupCollectionProvider.ApiDescriptionGroups
             .Items
             .SelectMany(group =&gt group.Items)
             .Select(apiDesc =&gt <span class="key">new</span>
             {
                 HttpMethod = apiDesc.HttpMethod,
                 RelativePath = apiDesc.RelativePath,
                 ActionName = apiDesc.ActionDescriptor.DisplayName,
                 Parameters = apiDesc.ParameterDescriptions.Select(param =&gt <span class="key">new</span>
                 {
                     param.Name,
                     param.Type,
                     param.Source
                 })
             });

        <span class="key">return</span> Ok(apiDescriptions);
    }
} </code></pre>

</div>



<p class="custp1 p-mb-0">Tools like Swagger (using Swashbuckle or NSwag) can automatically use ApiExplorer metadata to generate interactive API documentation.</p>



<br>



<p class="p-mb-0"><span style="border: 1px solid lightblue; padding: 7px 10px; border-radius: 10px;"><em><mark style="background-color:rgba(0, 0, 0, 0);color:#00008b" class="has-inline-color"><strong>read full post:</strong></mark></em> <a href="/add-swagger-documentation-in-net-core-api/" target="_blank" rel="noreferrer noopener"><span class="cLink3">How to Add Swagger in Web API .net core?</span></a></span></p>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you configure CORS policy for different environments?</strong></h3>



<p class="custp1 p-mb-0">To apply different Cross-Origin Resource Sharing (CORS) policies for different environments (e.g., Development, Staging, Production) in a Web API  ASP.NET Core, you can define environment-specific settings in your <strong>Startup.cs</strong> file. Here are the steps to configure CORS:</p>



<p class="custp1 p-mb-0"><strong>1) Add CORS Services</strong>: First, you need to add CORS services in the <strong>ConfigureServices</strong> method and configure different CORS policies for each environment.</p>



<p class="custp1 p-mb-0"><strong>2) Apply the CORS Policy Based on the Environment</strong>: In the <strong>Configure</strong> method, apply the appropriate CORS policy based on the environment in which the application is running.</p>



<button class="shbtn" id="shbtn74267" onclick="showHideBlock(74267)">&#9660; <u>Show example</u></button>
<div id="shdiv74267" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
	<span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
	{
		<span class="com">// Add CORS services</span>
		services.<span style="background:#f2f19d;">AddCors</span>(options =&gt
		{
			options.<b>AddPolicy</b>(name: <span class="str">"<span style="background:#f2f19d;">DevelopmentCorsPolicy</span>"</span>, builder =&gt
			{
				builder.WithOrigins(<span class="str">"http://localhost:58794"</span>,
									<span class="str">"http://localhost:58794/"</span>)
						.AllowAnyOrigin()
						.AllowAnyMethod()
						.AllowAnyHeader();
			});

			options.<b>AddPolicy</b>(name: <span class="str">"<span style="background:#f2f19d;">ProductionCorsPolicy</span>"</span>, builder =&gt
			{
				builder.WithOrigins(<span class="str">"https://your-production-site.com"</span>)
					   .AllowAnyMethod()
					   .AllowAnyHeader();
			});
		});
	}

	<span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		<span class="com">// Apply the CORS Policy</span>
		<span class="key">if</span> (env.IsDevelopment())
		{
			app.<span style="background:#f2f19d;">UseCors(<span class="str">"DevelopmentCorsPolicy"</span>)</span>;
		}
		<span class="key">else</span> <span class="key">if</span> (env.IsProduction())
		{
			app.<span style="background:#f2f19d;">UseCors(<span class="str">"ProductionCorsPolicy"</span>)</span>;
		}
	}
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle large data sets in Web API?</strong></h3>



<p class="custp1 p-mb-0">Here are some strategies to manage large data sets effectively:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Pagination</strong>: Breaks data into manageable pages.</li>



<li><strong>Lazy Loading</strong>: Loads data only when needed.</li>



<li><strong>Filtering</strong>: Narrows down the data set.</li>



<li><strong>Sorting</strong>: Orders data for easier navigation.</li>



<li><strong>Data Streaming</strong>: Sends data as it&#8217;s processed.</li>



<li><strong>Compression</strong>: Reduces the size of data sent over the network.</li>



<li><strong>Asynchronous Processing</strong>: Improves responsiveness.</li>



<li><strong>Caching</strong>: Reduces database load for frequently requested data.</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between synchronous and asynchronous operations in Web API?</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th>Synchronous Operations</th>
            <th>Asynchronous Operations</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Blocks the thread until the task is complete</td>
            <td>Does not block the thread, allowing other tasks to run</td>
        </tr>
        <tr>
            <td>Can lead to performance issues in I/O-bound tasks</td>
            <td>Improves performance, especially for I/O-bound tasks</td>
        </tr>
        <tr>
            <td>Less scalable, as each request can tie up a thread</td>
            <td>More scalable, freeing up threads for other requests</td>
        </tr>
        <tr>
            <td>Easier to implement and understand</td>
            <td>More complex, requires understanding of async/await</td>
        </tr>
        <tr>
            <td>Best suited for simple, short-running tasks</td>
            <td>Ideal for I/O-bound tasks that take time to complete (database, calling external services, or file I/O operations)</td>
        </tr>
    </tbody>
</table>



<button class="shbtn" id="shbtn10813" onclick="showHideBlock(10813)">&#9660; <u>Show example</u></button>
<div id="shdiv10813" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Synchronous call &#8211; Example</b></div>
<pre class="pchl"><code>[<span class="custkey">HttpGet</span>]
<span class="key">public</span> IActionResult GetData()
{
    <span class="key">var</span> data = _context.Data.ToList();  <span class="com">// This is a synchronous call</span>
    <span class="key">return</span> Ok(data);
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Asynchronous call &#8211; Example</b></div>
<pre class="pchl"><code>[<span class="custkey">HttpGet</span>]
<span class="key">public</span> <span class="key" style="background:#f2f19d;">async</span> Task&lt;IActionResult&gt GetDataAsync()
{
    <span class="key">var</span> data = <span class="key" style="background:#f2f19d;">await</span> _context.Data.<span style="background:#f2f19d;">ToListAsync()</span>;  <span class="com">// This is an asynchronous call</span>
    <span class="key">return</span> Ok(data);
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you ensure the security of sensitive data in Web API responses?</strong></h3>



<p class="custp1 p-mb-0">Here are several strategies to achieve this:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Use HTTPS</strong> and Encrypt Sensitive Data.</li>



<li>Restrict Data by implementing <strong>Role-Based Access</strong>.</li>



<li><strong>Use DTOs</strong> (Data Transfer Objects) and expose only necessary fields or data.</li>



<li>Implement detailed <strong>logging and auditing</strong> of API requests and responses, especially when sensitive data is accessed. </li>



<li>Regularly <strong>review logs</strong> to detect and respond to any suspicious activity.</li>



<li>Implement <strong>Content Security Policy (CSP) headers</strong> to help prevent cross-site scripting (XSS) attacks, which can lead to the exposure of sensitive data.</li>



<li><strong>Ensure Input Validation</strong>, incoming requests are properly validated and sanitized to prevent injection attacks.</li>



<li><strong>Add security headers</strong> like <span class="spanHT">X-Content-Type-Options</span>, <span class="spanHT">X-Frame-Options</span>, <span class="spanHT">Strict-Transport-Security</span>, etc., to protect against common web vulnerabilities.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are cross-cutting concerns in Web API, and how do you address them?</strong></h3>



<p class="custp1 p-mb-0"><strong>Cross-cutting concerns</strong> in a Web API are aspects of the application that affect multiple layers or components of the application. These concerns are not specific to any one piece of functionality but are needed across different parts of the system. Examples of cross-cutting concerns include logging, authentication, authorization, error handling, data validation, caching, exception handling, Response Formatting, and Rate Limiting. </p>



<p class="custp1 p-mb-0"><strong>Different ways to address Cross-Cutting Concerns:</strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Configuring Middleware:</strong> It allows you to execute code before and after the request is processed by the application. For example, you can implement logging, authentication, and error handling as middleware components.</li>



<li><strong>Creating Filters:</strong> Filters like AuthorizationFilter, ActionFilter, ExceptionFilter, and ResultFilter that can be applied at the controller or action level.</li>



<li><strong>Implementing Dependency Injection (DI):</strong> Use DI to manage dependencies such as logging services, authentication handlers, and configuration services.</li>



<li><strong>Applying Attributes:</strong> You can create a custom [ValidateModel] attribute to enforce model validation.</li>



<li><strong>Global Configuration</strong>: Configure global settings in the Startup.cs files like response formatting and security policies.</li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the role of IServiceCollection in configuring Web API services?</strong></h3>



<p class="custp1 p-mb-0"><strong>IServiceCollection</strong> is used to register and configure services that the application will use during its runtime. This registration is typically done in the Startup.cs file as part of the application&#8217;s dependency injection (DI) setup. </p>



<p class="custp1 p-mb-0"><strong>Key Roles of IServiceCollection:</strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Service Registration</strong>: It is used to register services with different lifetimes (e.g., singleton, scoped, transient) that your application depends on. This allows you to inject these services into controllers, middleware, or other services as needed.</li>



<li><strong>Middleware and Framework Services</strong>: It is used to register framework services, such as authentication, authorization, logging, and configuration services.</li>



<li><strong>Dependency Injection (DI)</strong>: It facilitates the Dependency Injection (DI) pattern allowing you to register services and configure how they should be resolved.</li>



<li><strong>Extensibility</strong>: The IServiceCollection interface is extensible, allowing you to add custom service registration extensions. This is often used in third-party libraries or to encapsulate complex service registrations into simple extension methods.</li>
</ul>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement a custom JSON converter in Web API?</strong></h3>



<p class="custp1 p-mb-0">To implement a custom JSON converter in a Web API, you can create a custom JSON converter by inheriting from the <span class="spanHT">JsonConverter</span> class in .NET. This allows you to control how specific types are serialized and deserialized to and from JSON. </p>



<p class="custp1 p-mb-0"><strong>Steps to Implement a Custom JSON Converter:</strong> </p>



<ol class="ol1 ol1-mb-0">
<li class="custp1">
<strong>Create a Custom JsonConverter:</strong> Create a class that inherits from <span class="spanHT">JsonConverter&lt;T&gt;</span>, where <span class="spanHT">T</span> is the type you want to customize the serialization and deserialization process for. Override the <span class="spanHT">Read</span> and <span class="spanHT">Write</span> methods to define the custom logic.
<div>
<button class="shbtnlist" id="shbtn80536" onclick="showHideBlock(80536)">&#9660; <u>Show example</u></button>
<div id="shdiv80536" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> CustomDateTimeConverter : <span style="background:#f2f19d;">JsonConverter&lt;DateTime&gt</span>
{
    <span class="key">private</span> <span class="key">readonly</span> <span class="key">string</span> _format;

    <span class="key">public</span> CustomDateTimeConverter(<span class="key">string</span> format)
    {
        _format = format;
    }

    <span class="key">public</span> <span class="key">override</span> DateTime <span style="background:#f2f19d;">Read</span>(<span class="key">ref</span> Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        <span class="key">return</span> DateTime.ParseExact(reader.GetString(), _format, <span class="key">null</span>);
    }

    <span class="key">public</span> <span class="key">override</span> <span class="key">void</span> <span style="background:#f2f19d;">Write</span>(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(_format));
    }
} </code></pre>
</div>
</div>
</li>


<li class="custp1">
<strong>Register the Custom Converter:</strong> Register the custom JSON converter globally in the Startup.cs file.
<div>
<button class="shbtnlist" id="shbtn92240" onclick="showHideBlock(92240)">&#9660; <u>Show example</u></button>
<div id="shdiv92240" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
    <span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
            .AddJsonOptions(options =&gt
            {
                options.<span style="background:#f2f19d;">JsonSerializerOptions.Converters.Add(<span class="key">new</span> CustomDateTimeConverter(<span class="str">"yyyy-MM-dd"</span>))</span>;
            });
    }

    <span class="com">// Other methods</span>
} </code></pre>
</div>
</div>
</li>


<li class="custp1">
<strong>Use the Custom Converter in a Specific Property:</strong> If you want to use the custom converter for specific properties rather than globally, you can apply the <strong>[JsonConverter]</strong> attribute to the property.
<div>
<button class="shbtnlist" id="shbtn633" onclick="showHideBlock(633)">&#9660; <u>Show example</u></button>
<div id="shdiv633" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> MyModel
{
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span style="background:#f2f19d;">[JsonConverter(<span class="key">typeof</span>(<b>CustomDateTimeConverter</b>), <span class="str">"yyyy-MM-dd"</span>)]</span>
    <span class="key">public</span> DateTime DateOfBirth { get; set; }
} </code></pre>
</div>
</div>
</li>

</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle streaming responses in Web API?</strong></h3>



<p class="custp1 p-mb-0">Streaming can be handled using the Controller&#8217;s base <span class="spanHT">File()</span> method or <span class="spanHT">FileStreamResult</span> class. </p>



<p class="custp1 p-mb-0"><span class="spanHT">FileStreamResult</span> can be used to stream a file from the server to the client without loading the entire file into memory. </p>



<p class="custp1 p-mb-0">In the same way, the <span class="spanHT">File</span> method has several overloads that also accept a Stream as an input parameter and return a <span class="spanHT">FileStreamResult</span>. </p>



<button class="shbtn" id="shbtn79812" onclick="showHideBlock(79812)">&#9660; <u>Show example</u></button>
<div id="shdiv79812" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Using FileStreamResult &#8211; Example</b></div>
<pre class="pchl"><code>[<span class="custkey">HttpGet</span>(<span class="str">"download-file"</span>)]
<span class="key">public</span> IActionResult DownloadFile()
{
    <span class="key">var</span> filePath = <span class="str">"path/to/large/file.zip"</span>;
    <span class="key">var</span> stream = <span class="key">new</span> FileStream(filePath, FileMode.Open, FileAccess.Read);
    <span class="key">return</span> <span class="key">new</span> <span style="background:#f2f19d;">FileStreamResult</span>(stream, <span class="str">"application/octet-stream"</span>)
    {
        FileDownloadName = <span class="str">"file.zip"</span>
    };
} </code></pre>


<br><br><br>
<div style="padding-left: 0.3125rem;"><b>Using Controller.File method &#8211; Example</b></div>
<pre class="pchl"><code>[<span class="custkey">HttpGet</span>(<span class="str">"DownloadFile/{Id}"</span>)]
<span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt DownloadFileAsync(<span class="key">int</span> Id)
{
    <span class="key">if</span> (recipe != <span class="key">null</span>)
    {
		MemoryStream ms = <span class="key">new</span> MemoryStream();
		CloudBlob file = <span class="com">// get file from azure</span>

		<span class="key">if</span> (<span class="key">await</span> file.ExistsAsync())
		{
			<span class="key">await</span> file.DownloadToStreamAsync(ms);
			<span class="custkey">Stream</span> blobStream = file.OpenReadAsync().Result;
			<span class="key">return</span> <span style="background:#f2f19d;">File</span>(blobStream, file.Properties.ContentType, file.Name);
		}
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use the ProblemDetails class for standardized error responses?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">ProblemDetails</span> class is used to provide standardized error responses that conform to the &#8216;RFC 7807&#8217; specification for problem details. This helps create consistent and informative error responses across your API.</p>



<button class="shbtn" id="shbtn24272" onclick="showHideBlock(24272)">&#9660; <u>Show example</u></button>
<div id="shdiv24272" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1) Basic Usage in an Action Method</b></div>
<div style="padding-left: 0.3125rem;" class="custp1">You can return a &#39;ProblemDetails&#39; object directly from an action method to provide detailed error information.</div>
<pre class="pchl"><code>[<span class="custkey">HttpGet</span>(<span class="str">"example"</span>)]
<span class="key">public</span> IActionResult GetExample()
{
    <span class="key">if</span> (<span class="com">/* some error condition */</span>)
    {
        <span class="key">var</span> <b>problemDetails</b> = <span class="key">new</span> <span style="background:#f2f19d;">ProblemDetails</span>
        {
            Status = StatusCodes.Status400BadRequest,
            Title = <span class="str">"Invalid request"</span>,
            Detail = <span class="str">"The request parameters are not valid."</span>,
            Instance = HttpContext.Request.Path
        };

        <span class="key">return</span> BadRequest(<b>problemDetails</b>);
    }

    <span class="com">// Normal response</span>
    <span class="key">return</span> Ok();
} </code></pre>



<br><br><br>
<div style="padding-left: 0.3125rem;"><b>2) Extend and Customize ProblemDetails</b></div>
<div style="padding-left: 0.3125rem;" class="custp1">You can extend the &#39;ProblemDetails&#39; class to include additional information relevant to your application.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> CustomProblemDetails : <span style="background:#f2f19d;">ProblemDetails</span>
{
    <span class="key">public</span> <span class="key">string</span> ErrorCode { get; set; }
    <span class="key">public</span> string[] ErrorMessages { get; set; }
}

[<span class="custkey">HttpGet</span>(<span class="str">"custom-example"</span>)]
<span class="key">public</span> IActionResult GetCustomExample()
{
    <span class="key">var</span> <b>problemDetails</b> = <span class="key">new</span> <span style="background:#f2f19d;">CustomProblemDetails</span>
    {
        Status = StatusCodes.Status400BadRequest,
        Title = <span class="str">"Validation Error"</span>,
        Detail = <span class="str">"One or more validation errors occurred."</span>,
        Instance = HttpContext.Request.Path,
        ErrorCode = <span class="str">"VAL123"</span>,
        ErrorMessages = new[] { <span class="str">"Field1 is required."</span>, <span class="str">"Field2 must be a valid email address."</span> }
    };

    <span class="key">return</span> BadRequest(<b>problemDetails</b>);
} </code></pre>



<br><br><br>
<div style="padding-left: 0.3125rem;"><b>3) Global Exception Handling</b></div>
<div style="padding-left: 0.3125rem;" class="custp1">You can configure global exception handling in &#39;Startup.cs&#39; to automatically return &#39;ProblemDetails&#39; for unhandled exceptions.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseExceptionHandler(config =&gt
    {
        config.Run(<span class="key">async</span> context =&gt
        {
            <span class="key">var</span> exception = context.Features.Get&lt;IExceptionHandlerFeature&gt()?.Error;
            <span class="key">var</span> <b>problemDetails</b> = <span class="key">new</span> <span style="background:#f2f19d;">ProblemDetails</span>
            {
                Status = StatusCodes.Status500InternalServerError,
                Title = <span class="str">"An unexpected error occurred."</span>,
                Detail = exception?.Message,
                Instance = context.Request.Path
            };

            context.Response.StatusCode = StatusCodes.Status500InternalServerError;
            context.Response.ContentType = <span class="str">"application/problem+json"</span>;

            <span class="key">await</span> context.Response.WriteAsJsonAsync(<b>problemDetails</b>);
        });
    });

    <span class="com">// Other middlewares...</span>
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement background services in ASP.NET Core Web API?</strong></h3>



<p class="custp1 p-mb-0">Background services can be implemented using the <span class="spanHT">IHostedService</span> interface or by deriving from the <span class="spanHT">BackgroundService</span> class. Background services are long-running processes that can execute independently of the main web request processing pipeline.</p>



<br>



<p class="p-mb-0"><strong>When to use?</strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Processing Queue Messages:</strong> Continuously process messages from a queue.</li>



<li><strong>Scheduled Tasks:</strong> Perform periodic tasks like clearing caches or sending notifications.</li>



<li><strong>Polling Services:</strong> Poll external services or APIs for updates.</li>
</ul>



<br>



<p class="p-mb-0"><strong>Steps to Implement a Background Service:</strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Create a Background Service Class:</strong> Implement the <span class="spanHT">IHostedService</span> interface or derive from <span class="spanHT">BackgroundService</span>.</li>



<li><strong>Override the ExecuteAsync Method:</strong> The <span class="spanHT">ExecuteAsync</span> method contains the logic for the background task. It runs in the background and is called when the service starts.</li>



<li><strong>Register the Background Service:</strong> Register the background service in the Dependency Injection (DI) Container using <span class="spanHT">AddHostedService&lt;T&gt;()</span> in the Startup.cs file.</li>
</ol>



<button class="shbtn" id="shbtn24407" onclick="showHideBlock(24407)">&#9660; <u>Show example</u></button>
<div id="shdiv24407" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1. Create the Background Service Class</b></div>
<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Threading;
<span class="key">using</span> System.Threading.Tasks;
<span class="key">using</span> Microsoft.Extensions.Hosting;
<span class="key">using</span> Microsoft.Extensions.Logging;

<span class="key">public</span> <span class="key">class</span> MyBackgroundService : <span style="background:#f2f19d;">BackgroundService</span>
{
    <span class="key">private</span> <span class="key">readonly</span> ILogger&lt;MyBackgroundService&gt _logger;

    <span class="key">public</span> MyBackgroundService(ILogger&lt;MyBackgroundService&gt logger)
    {
        _logger = logger;
    }

    <span class="key">protected</span> <span class="key">override</span> <span class="key">async</span> Task <span style="background:#f2f19d;">ExecuteAsync</span>(CancellationToken stoppingToken)
    {
        _logger.LogInformation(<span class="str">"MyBackgroundService is running."</span>);

        <span class="key">while</span> (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation(<span class="str">"Doing background work..."</span>);
            <span class="key">await</span> Task.Delay(1000, stoppingToken); <span class="com">// Simulate work</span>
        }

        _logger.LogInformation(<span class="str">"MyBackgroundService is stopping."</span>);
    }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>2. Register the Service</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
	<span class="key">public</span> <span class="key">void</span> ConfigureServices(IServiceCollection services)
	{
		services.<span style="background:#f2f19d;">AddHostedService&lt;MyBackgroundService&gt()</span>;
	}
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement HTTP/2 in Web API?</strong></h3>



<p class="custp1 p-mb-0">Implementing HTTP/2 in an ASP.NET Core Web API application primarily involves configuring the server to support the HTTP/2 protocol. ASP.NET Core has built-in support for HTTP/2 on Kestrel, IIS, and other web servers. </p>



<p class="custp1 p-mb-0"><strong>Steps to Implement HTTP/2: </strong></p>



<p class="custp1 p-mb-0"><strong>1. Configure Kestrel for HTTP/2 (Default Configuration):</strong> Kestrel, the default web server in ASP.NET Core, supports HTTP/2 out of the box when using HTTPS. Typically, no additional configuration is required, but you can customize the setup if needed.</p>



<button class="shbtn" id="shbtn35767" onclick="showHideBlock(35767)">&#9660; <u>Show example</u></button>
<div id="shdiv35767" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>In Program.cs file</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> IHostBuilder CreateHostBuilder(string[] args) =&gt
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =&gt
            {
                webBuilder.<span style="background:#f2f19d;">ConfigureKestrel</span>(serverOptions =&gt
                {
                    <span class="com">// Optional: Configure Kestrel for HTTP/2</span>
                    serverOptions.ListenAnyIP(5001, listenOptions =&gt
                    {
                        listenOptions.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.<span style="background:#f2f19d;"><b>Http2</b></span>;
                        listenOptions.<b>UseHttps()</b>; <span class="com">// HTTP/2 requires HTTPS</span>
                    });
                });            
            });
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>In Startup.cs file</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
	<span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		app.UseEndpoints(endpoints =&gt
		{
			endpoints.<span style="background:#f2f19d;">MapGet</span>(<span class="str">"/"</span>, () =&gt <span class="str">"Hello, HTTP/2!"</span>);
		});
	}
} </code></pre>

</div>



<p class="custp1 p-mb-0"><strong>2. Configure IIS for HTTP/2:</strong> If hosting on IIS, HTTP/2 is automatically enabled if the following conditions are met: </p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>The application is served over HTTPS.</li>



<li>The server runs on Windows Server 2016 or later, or Windows 10 or later.</li>
</ul>



<p class="custp1 p-mb-0">No specific changes are needed in the application code.</p>



<p class="custp1 p-mb-0"><strong>3. Enable HTTP/2 for Other Servers:</strong> For other servers like Nginx or Apache, HTTP/2 must be enabled at the server level. Configuration may differ depending on the server.</p>



<p class="custp1 p-mb-0"><strong>4. Client Compatibility:</strong> Ensure that the clients consuming the API are compatible with HTTP/2.</p>



<br>



<p class="custp1 p-mb-0"><strong>Key Points:</strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>HTTPS Requirement:</strong> HTTP/2 requires HTTPS. Ensure SSL/TLS is properly configured.</li>



<li><strong>Automatic Fallback:</strong> If a client doesn’t support HTTP/2, the server automatically falls back to HTTP/1.1.</li>



<li><strong>Performance Benefits:</strong> HTTP/2 offers performance improvements like multiplexing, header compression, and more efficient resource loading.</li>
</ul>



<br>



<p class="custp1 p-mb-0">You can <strong>configure HTTP/2 and HTTP/1.1 Fallback</strong> in Kestrel and this setup allows the server to handle both HTTP/2 and HTTP/1.1 requests, providing flexibility for clients with varying protocol support.</p>



<button class="shbtn" id="shbtn71107" onclick="showHideBlock(71107)">&#9660; <u>Show example</u></button>
<div id="shdiv71107" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>In Program.cs file</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> IHostBuilder CreateHostBuilder(string[] args) =&gt
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =&gt
            {
                webBuilder.<span style="background:#f2f19d;">ConfigureKestrel</span>(serverOptions =&gt
                {
                    serverOptions.ListenAnyIP(5001, listenOptions =&gt
                    {
                        listenOptions.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.<span style="background:#f2f19d;"><b>Http1AndHttp2</b></span>;
                        listenOptions.<b>UseHttps()</b>;
                    });
                });            
            });
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>In Startup.cs file</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Startup
{
	<span class="key">public</span> <span class="key">void</span> Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		app.UseEndpoints(endpoints =&gt
		{
			endpoints.<span style="background:#f2f19d;">MapGet</span>(<span class="str">"/"</span>, () =&gt <span class="str">"Hello, HTTP/2 with fallback to HTTP/1.1!"</span>);
		});
	}
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is gRPC, and how does it compare to Web API?</strong></h3>



<p class="custp1 p-mb-0">gRPC is a high-performance, open-source framework developed by Google for building remote procedure call (RPC) APIs. It allows clients and servers to communicate directly by calling methods as if they were local, even though they might be on different machines. gRPC uses HTTP/2 for transport, and efficient binary serialization with Protocol Buffers (protobufs) as the Interface Definition Language (IDL), and offers features like bidirectional streaming, multiplexing of requests, header compression, and more.</p>



<br>



<p class="p-mb-0"><strong>Comparison Between gRPC and Web API:</strong></p>



<div style="height:18.75rem; overflow-y:scroll; border: 1px solid #d3d3d3;">
<table style="margin: 0;">
    <thead>
        <tr>
            <th>gRPC</th>
            <th>Web API</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>HTTP/2</td>
            <td>HTTP/1.1 (typically), but HTTP/2 is also supported</td>
        </tr>
        <tr>
            <td>Protocol Buffers (binary format)</td>
            <td>JSON (text format)</td>
        </tr>
        <tr>
            <td>High performance, low latency due to HTTP/2 and Protocol Buffers</td>
            <td>Good performance, but generally slower than gRPC</td>
        </tr>
        <tr>
            <td>Supports client, server, and bidirectional streaming</td>
            <td>Limited streaming support (requires additional work)</td>
        </tr>
        <tr>
            <td>Supports multiple languages (e.g., C#, Java, Go, Python)</td>
            <td>Primarily focused on .NET languages, but can work with any HTTP-capable language</td>
        </tr>
        <tr>
            <td>Best for high-performance, low-latency scenarios, microservices</td>
            <td>Best for RESTful services, CRUD operations, simpler APIs</td>
        </tr>
        <tr>
            <td>Strongly typed contracts, defined with Protocol Buffers</td>
            <td>Typically defined with OpenAPI (Swagger)</td>
        </tr>
        <tr>
            <td>Strong tooling support for generating client/server code</td>
            <td>Strong tooling support for OpenAPI/Swagger</td>
        </tr>
        <tr>
            <td>Requires learning Protocol Buffers and gRPC concepts</td>
            <td>Easier to get started with for developers familiar with REST APIs</td>
        </tr>
        <tr>
            <td>Not natively supported in browsers</td>
            <td>Fully supported in browsers</td>
        </tr>
        <tr>
            <td>Uses SSL/TLS and built-in authentication mechanisms</td>
            <td>Uses SSL/TLS, OAuth, JWT, and other security methods</td>
        </tr>
    </tbody>
</table>
</div>
<br>



<p class="custp1 p-mb-0"><strong>When to Use?</strong></p>



<table style="margin: 0;">
    <thead>
        <tr>
            <th>Use gRPC</th>
            <th>Use Web API</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>When performance and efficiency are critical, especially in microservices architectures.</td>
            <td>When building RESTful services that need to be consumed by a wide variety of clients, including web browsers.</td>
        </tr>
        <tr>
            <td>When you need to support streaming scenarios (e.g., real-time chat, video streaming).</td>
            <td>When simplicity and ease of integration with existing HTTP infrastructure are important.</td>
        </tr>
        <tr>
            <td>When you require strongly-typed contracts and a binary data format.</td>
            <td>When working with JSON or text-based data formats is preferable.</td>
        </tr>
    </tbody>
</table>



<br><br><br><br>



<div id="download-questions" style="border: solid 1px lightblue; padding: 10px;">
<button class="shbtn" style="float: right; border-radius: 20px;" onclick="saveQuestionsAsPDF()">Download</button>
<div><span style="font-weight: bold; font-size: 20px; color: #7100e2;">Download all Questions as .PDF</span></div>
<div id="questions"><br><br><center><span style="color:#808080;"><i>loading&#8230;</i></span></center></div>
</div>



<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>



<style>
.shbtn {
    color: #fff;
    padding: 6px 12px;
    margin-top: 8px;
}
.shbtnlist {
    color: #fff;
    padding: 3px 9px;
}
.shdt {
    box-shadow: lightblue 0px 1px 2px;
}
pre {
    margin-bottom: 0;
}
tbody>tr>th {
    font-weight: bold;
}
.p-lp-15 {
    padding-left: 0.9375rem;
}
</style>

<script>
	function showHideBlock(val) {
		var btnx = document.getElementById("shbtn" + val);
		var divx = document.getElementById("shdiv" + val);

		if (divx.style.display === "none") {
			divx.style.display = "block";
			btnx.innerHTML = "&#9650; <u>Hide example</u>";
		} else {
			divx.style.display = "none";
			btnx.innerHTML = "&#9660; <u>Show example</u>";
		}
	}
</script>



<script>
window.onload = function (){
	var shbtnarr = document.getElementsByClassName("shbtn");
	var alreadySeen ={};
	console.log("shbtn count: " + shbtnarr.length);
	console.log("find duplicate - Start ---"); 
	for (element of shbtnarr) {
		if (alreadySeen[element.id]){
			console.log(element.id);
			alreadySeen[element.id] = false;
		}
		else {
			alreadySeen[element.id] = true;
		}
	}
	console.log("find duplicate - End ---"); 
	console.log()
	console.log("--- sh(alreadySeen) ids ---");
	console.log(alreadySeen);
	/* for (var key in alreadySeen)
	{
		console.log(key + " : " +  alreadySeen[key]);
	} */


	/*Sl.No for H3*/
	var h3arr = document.getElementsByClassName("hLBRed");
	var questions = document.getElementById("questions");
	questions.innerHTML = "<br><br><div><h2><center><b><u>Web API Interview Questions</u></b></center></h2></div><br>";
	var count = 1;
	var searchResult = "";
	for (h3 of h3arr) {
		questions.innerHTML = questions.innerHTML + "<div>" + "<b>" + count + ")</b> " + h3.innerText.replace(/[^\w\s#?.,=<>()[]]/gi, '').replace('<','&lt;').replace('>','&gt;') + "</div>";
		h3.innerHTML = "<b>" + count + ") " + h3.innerHTML + "</b>";
		h3.id = "q" + count;
		searchResult += '<div class="filter-list-item"><a href="#' + h3.id + '">' + h3.innerText + '</a></div>'
		count++;
	}

	document.getElementById('myList').innerHTML = searchResult;
};


/* Print Questions */
function saveQuestionsAsPDF(divId, title) { 
	if (document.getElementById("questions").innerText.trim().length == 0) return;

	var doc = new jsPDF();
	doc.fromHTML('<html><head></head><body><div>https://www.codeindotnet.com/all-interview-questions-and-answers/</div>' + document.getElementById("questions").innerHTML + '<br><br><br><div><b>See Other Questions &amp; Answers:</b> https://www.codeindotnet.com/all-interview-questions-and-answers/</div></body></html>');
	doc.save('web-api-interview-questons.pdf');
}

</script>



<script type="text/javascript">
        document.getElementById("myInput").addEventListener("keyup",
    		function searchFilter() {
    			// Declare variables
    			var input, filter, div, divs, a, i;
    			input = document.getElementById('myInput').value.replace(/\s{2,}/g, ' ').trim().toUpperCase();
				arrFilters = input.split(' ');
    			div = document.getElementById('myList');
    			divs = div.getElementsByClassName('filter-list-item');
				
    			if (document.getElementById("myList").style.display == "none"){
    				document.getElementById("myList").style.display = "block";
    			}

				if(input.length == 0){
					for (i = 0; i < divs.length; i++) {
						divs[i].style.display = '';						
					}
				}
				else {
					// Loop through all list items, and hide those who don't match the search query
					for (i = 0; i < divs.length; i++) {
						a = divs[i].getElementsByTagName('a')[0];
						divs[i].style.display = 'none';
						for (j = 0; j < arrFilters.length; j++) {
							if ((arrFilters[j].length > 0) && (a.innerHTML.toUpperCase().indexOf(arrFilters[j]) > -1)) {
								divs[i].style.display = '';
								break;
							} 						
						}
						
					}
				}
    
		});
    </script>



<script>
function displayAllResult(){
	document.getElementById("myInput").value = ''
	div = document.getElementById('myList');
	divs = div.getElementsByClassName('filter-list-item');
	for (i = 0; i < divs.length; i++) {
		divs[i].style.display = '';						
	}
}
</script>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/web-api-interview-questions-answers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>43 Must-known OOPs Interview Questions &#038; Answers</title>
		<link>https://www.codeindotnet.com/oops-interview-questions-answers/</link>
					<comments>https://www.codeindotnet.com/oops-interview-questions-answers/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 14 Aug 2024 15:07:11 +0000</pubDate>
				<category><![CDATA[Interview Questions Answers]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=7894</guid>

					<description><![CDATA[Here are the top 43 OOPs interview questions and answers for beginners and professionals. Other Interview Questions &#8211; C#, SQL OOPs Interview Questions And Answers Download all Questions as .PDF Search: Clear × What is OOPs? Object-Oriented Programming (OOP) is a way of writing programs using &#8220;objects,&#8221; which are like building blocks. Each object can [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>


<div class="wp-block-image is-style-default">
<figure class="aligncenter size-large"><img decoding="async" src="/img/1/qa/oops-interview-questions-answers-2.jpg" alt="OOPs Interview Questions and Answers"/></figure></div>


<br>



<p>Here are the top 43 OOPs interview questions and answers for beginners and professionals. </p>



<p class="has-text-align-right"><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"><strong>Other Interview Questions &#8211;</strong></mark> <strong><a href="https://www.codeindotnet.com/csharp-interview-questions-answers/" data-type="post" data-id="8095">C#</a></strong>, <strong><a href="https://www.codeindotnet.com/sql-interview-questions-answers/" data-type="post" data-id="7407">SQL</a></strong></p>



<br>



<h2 class="wp-block-heading h2Cust1"><strong>OOPs Interview Questions And Answers</strong></h2>



<p class="has-text-align-right"><strong><a href="#download-questions" data-type="internal" data-id="#download-questions">Download all Questions as .PDF</a></strong></p>



<div id="searchPopup">
	<div class="popup-header">			
		<span style="font-weight:bold;">Search: </span>
		<input type="text" id="myInput" autocomplete="off" placeholder=" type keyword(s) &amp; filter Questions..." onclick="document.getElementById('myList').style.display = 'block'; document.getElementById('btnpopclose').style.display = 'block';">
		<button onclick="displayAllResult();" style="padding: 5px 9px; border-radius: 10px; color:#fff;" >Clear</button>
		<button id="btnpopclose" class="popup-close" onclick="document.getElementById('myList').style.display = 'none'; document.getElementById('btnpopclose').style.display = 'none';">×</button>
	</div>
	<div id="myList"></div>		
</div>



<style>
.popup-close {
    font-size: 1.25rem;
    font-weight: 700;
    padding: .3125rem .625rem;
    border-radius: .3125rem;
    background-color: red;
    color: #fff;
    border: none;
    float: right;
    display: none;
    /*margin: -.3125rem;*/
}

#myInput{
width: calc(100% - 11.5625rem);
display:inline; 
border-radius: 10px; 
margin:0;
}

#searchPopup{
border: 1px solid #6a409759;
    padding: 10px;
    border-radius: 5px;
}

#myList{
line-height: 1.7; 
font-size: 16px; 
overflow-y: scroll; 
height: 250px; 
/*border-bottom: 3px lightgray solid;*/
display:none; 
margin-top: 15px;
}
</style>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is OOPs?</strong></h3>



<p class="custp1 p-mb-0">Object-Oriented Programming (OOP) is a way of writing programs using &#8220;objects,&#8221; which are like building blocks. Each object can hold data (attributes) and actions (methods) that work on the data. It makes easier to manage complex programs by breaking them into smaller, reusable parts. </p>



<p class="custp1 p-mb-0">The main <strong>principles of OOPs are</strong> &#8211; <span class="spanHT">Encapsulation</span>, <span class="spanHT">Abstraction</span>, <span class="spanHT">Inheritance</span>, <span class="spanHT">Polymorphism</span>.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Class?</strong></h3>



<p class="custp1 p-mb-0">A class is a blueprint for creating objects. It defines the attributes (data) and methods (actions) that the objects created from the class will have. Classes help organize and structure code by grouping related data and functions together.</p>



<button class="shbtn" id="shbtn82425" onclick="showHideBlock('82425')">&#9660; <u>Show example</u></button>
<div id="shdiv82425" style="display: none;">
<pre class="pchl"><code><span style="background:#f2f19d;"><span class="key">class</span> Demo</span>
{
    <span class="com">// Method of the class</span>
    <span class="key">public</span> <span class="key">void</span> DisplayInfo()
    {
        Console.WriteLine(<span class="str">"Welcome"</span>);
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Object?</strong></h3>



<p class="custp1 p-mb-0">An object is a self-contained unit that holds both data and actions. The data is called attributes, and the actions are called methods. Objects are like real-world things with properties and behaviors.</p>



<button class="shbtn" id="shbtn41250" onclick="showHideBlock(41250)">&#9660; <u>Show example</u></button>
<div id="shdiv41250" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="com">// Define a class named Car</span>
<span class="key">class</span> Car
{
    <span class="com">// Properties of the class</span>
    <span class="key">public</span> <span class="key">string</span> Make { get; set; }
    <span class="key">public</span> <span class="key">string</span> Model { get; set; }
    <span class="key">public</span> <span class="key">int</span> Year { get; set; }

    <span class="com">// Method of the class</span>
    <span class="key">public</span> <span class="key">void</span> DisplayInfo()
    {
        Console.WriteLine($<span class="str">"Car: {Year} {Make} {Model}"</span>);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="com">// Create an object of the Car class</span>
        <span style="background:#f2f19d;">Car myCar = <span class="key">new</span> Car();</span>

        <span class="com">// Set the properties of the object</span>
        myCar.Make = <span class="str">"Toyota"</span>;
        myCar.Model = <span class="str">"Camry"</span>;
        myCar.Year = 2020;

        <span class="com">// Call the method of the object</span>
        myCar.DisplayInfo();
    }
} </code></pre>

<div style="padding: 0.3125rem 0.3125rem 0.625rem 0.625rem;">
<p class="custp1 p-mb-0">The <b>Car</b> class is defined with three properties (Make, Model, and Year) and  also has a method DisplayInfo that prints the car’s details.</p>
<p class="custp1 p-mb-0">In the Main method, an object <b>myCar</b> of the Car class is created.</p>
</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between a Class and an Object</strong>?</h3>



<br>
<table>
    <thead>
        <tr>
            <th></th>
            <th>Class</th>
            <th>Object</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Definition</th>
            <td>A blueprint or template for creating objects</td>
            <td>An instance of a class</td>
        </tr>
        <tr>
            <th>Purpose</th>
            <td>Defines properties (attributes) and methods (behavior)</td>
            <td>Represents a specific entity with actual values</td>
        </tr>
        <tr>
            <th>Creation</th>
            <td>Defined using the class keyword</td>
            <td>Created using the new keyword</td>
        </tr>
        <tr>
            <th>Memory</th>
            <td>Does not occupy memory until an object is created</td>
            <td>Occupies memory when it is instantiated</td>
        </tr>
        <tr>
            <th>Example</th>
            <td>class Person { public string Name; public int Age; }</td>
            <td>Person person = new Person();</td>
        </tr>
        <tr>
            <th>Data</th>
            <td>Contains no data, only definitions</td>
            <td>Contains actual data and state</td>
        </tr>
        <tr>
            <th>Lifecycle</th>
            <td>Exists as long as the program is running (static context)</td>
            <td>Exists as long as it is referenced (dynamic context)</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Encapsulation?</strong></h3>



<p class="custp1 p-mb-0">Encapsulation means that a group of related properties, methods, and other memebers are treated as a single unit or object. It helps protect the data by restricting direct access from outside the object, allowing it to be accessed or modified only through defined methods. This is achieved by using access modifiers like private, public, protected, internal. </p>



<button class="shbtn" id="shbtn74558" onclick="showHideBlock(74558)">&#9660; <u>Show example</u></button>
<div id="shdiv74558" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="com"><b>// Encapsulation</b></span>
<span class="key">class</span> Person
{
    <span class="com">// Encapsulated private fields</span>
    <span class="key">private</span> <span class="key">string</span> name;

    <span class="com">// Public methods to access and modify private fields (encapsulation)</span>
    <span class="key">public</span> <span class="key">void</span> SetName(<span class="key">string</span> newName)
    {
        name = newName;
    }

    <span class="key">public</span> <span class="key">string</span> GetName()
    {
        <span class="key">return</span> name;
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        Person person = <span class="key">new</span> Person();

        <span class="com">// Using encapsulation to set and get Name</span>
        person.<b>SetName</b>(<span class="str">"John"</span>);
        Console.WriteLine(<span class="str">"Name: "</span> + person.<b>GetName</b>());
    }
} </code></pre>

<div style="padding: 0.3125rem 0.3125rem 0.625rem 0.625rem;">
<p class="custp1 p-mb-0">In this example, the Person class uses private fields and public methods to control access to the data, ensuring that the internal state cannot be modified directly.</p>
</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Abstraction?</strong></h3>



<p class="custp1 p-mb-0">Abstration means hiding the unnecessary details and showing only the essential features of an object.</p>



<p class="custp1 p-mb-0">In C#, we can implement the abstraction OOPs principle in two ways:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li>Using Interface</li>



<li>Using Abstract Classes and Abstract Methods</li>
</ol>



<button class="shbtn" id="shbtn6997" onclick="showHideBlock(6997)">&#9660; <u>Show example</u></button>
<div id="shdiv6997" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="com">// Abstract class</span>
<span style="background:#f2f19d;"><span class="key">abstract</span> <span class="key">class</span> Animal</span>
{
    <span class="com">// Abstract method (no body)</span>
    <span class="key">public</span> <span class="key">abstract</span> <span class="key">void</span> MakeSound();

    <span class="com">// Regular method</span>
    <span class="key">public</span> <span class="key">void</span> Sleep()
    {
        Console.WriteLine(<span class="str">"Sleeping..."</span>);
    }
}

<span class="com">// Interface</span>
<span style="background:#f2f19d;"><span class="key">interface</span> IAnimal</span>
{
    <span class="key">void</span> Eat();
}

<span class="com">// Derived class implementing abstract class and interface</span>
<span class="key">class</span> Dog : Animal, IAnimal
{
    <span class="com">// Providing implementation of abstract method</span>
    <span class="key">public</span> <span class="key">override</span> <span class="key">void</span> MakeSound()
    {
        Console.WriteLine(<span class="str">"Bark"</span>);
    }

    <span class="com">// Implementing interface method</span>
    <span class="key">public</span> <span class="key">void</span> Eat()
    {
        Console.WriteLine(<span class="str">"Eating..."</span>);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        Dog myDog = <span class="key">new</span> Dog();

        <span class="com">// Calling methods</span>
        myDog.MakeSound(); <span class="com">// Output: Bark</span>
        myDog.Sleep();     <span class="com">// Output: Sleeping...</span>
        myDog.Eat();       <span class="com">// Output: Eating...</span>
    }
} </code></pre>

<div style="padding: 0.3125rem 0.3125rem 0.625rem 0.625rem;">
	<p class="custp1 p-mb-0">In this example, the Animal abstract class and the IAnimal interface define methods without providing the implementation, which is then provided by the Dog class. This hides the complexity and shows only the necessary features.</p>
</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference between Encapsulation and Abstraction</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th>Encapsulation</th>
            <th>Abstraction</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Encapsulation hides the internal state of an object and requires all interaction to be performed through an object&#39;s methods.</td>
            <td>Abstraction hides complex implementation details and shows only the necessary features of an object.</td>
        </tr>
        <tr>
            <td>Achieved by using access modifiers (private, protected, public).</td>
            <td>Achieved by using abstract classes and interfaces.</td>
        </tr>
        <tr>
            <td>Focuses on restricting access to data.</td>
            <td>Focuses on hiding the complexity of the system.</td>
        </tr>
        <tr>
            <td>Ensures that the object&#39;s internal state cannot be directly accessed.</td>
            <td>Provides a high-level view of an object&#39;s functionality.</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>What is Inheritance</strong>?</strong></h3>



<p class="custp1 p-mb-0">Inheritance allows a new class to inherit properties and methods from an existing class. This promotes code reusability and establishes a relationship between classes. The class that is inherited from is called the base class (or parent class), and the class that inherits is called the derived class (or child class).</p>



<button class="shbtn" id="shbtn9781" onclick="showHideBlock(9781)">&#9660; <u>Show example</u></button>
<div id="shdiv9781" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="com">// Base class (Parent class)</span>
<span class="key">class</span> Animal
{
    <span class="key">public</span> <span class="key">void</span> Eat()
    {
        Console.WriteLine(<span class="str">"Eating..."</span>);
    }
}

<span class="com">// Derived class (Child class)</span>
<span style="background:#f2f19d;"><span class="key">class</span> Dog : Animal</span>
{
    <span class="key">public</span> <span class="key">void</span> Bark()
    {
        Console.WriteLine(<span class="str">"Barking..."</span>);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        Dog myDog = <span class="key">new</span> Dog();

        <span class="com">// Calling method from the base class</span>
        myDog.Eat(); <span class="com">// Output: Eating...</span>

        <span class="com">// Calling method from the derived class</span>
        myDog.Bark(); <span class="com">// Output: Barking...</span>
    }
} </code></pre>

<div style="padding: 0.3125rem 0.3125rem 0.625rem 0.625rem;">
<ul class="ol1-mb-0">
<li><b>Base Class (Animal):</b> This class contains a method Eat().</li>
<li><b>Derived Class (Dog):</b> This class inherits from the Animal class and adds its own method Bark().</li>
<li>In the Main method, an object of the Dog class is created. This object can access both the Eat method (inherited from Animal) and the Bark method (defined in Dog).</li>
</ul>
<p class="p-mb-0">You can also Implement Inheritance with Overriding.</p>
</div>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>What is Polymorphism</strong>?</strong></h3>



<p class="custp1 p-mb-0">Polymorphism allows a method to be defined in multiple ways in a class, enabling it to behave differently based on the object that invokes it.</p>



<p class="custp1 p-mb-0">Method overloading is achieved in three ways:</p>



<ul class="ol1 wp-block-list">
<li>Different number of parameters</li>



<li>Different types of parameters</li>



<li>Different order of parameters</li>
</ul>



<h4 class="wp-block-heading"><strong><em>Types of Polymorphism:</em></strong></h4>



<ol class="ol1-mb-0">
<li><strong>Compile-time Polymorphism:</strong> Also called as <strong>Static Polymorphism/ Method Overloading/ Early Binding</strong>. It Allows multiple methods in the same class to have the same name but different parameters. Achieved through method overloading and operator overloading.</li>
<button class="shbtn" id="shbtn91188" onclick="showHideBlock(91188)">&#9660; <u>Show example</u></button>
<div id="shdiv91188" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">class</span> MathOperations
{
    <span class="com">// Method to add two integers</span>
    <span class="key">public</span> <span class="key">int</span> <span style="background:#f2f19d;">Add(<span class="key">int</span> a, <span class="key">int</span> b)</span>
    {
        <span class="key">return</span> a + b;
    }

    <span class="com">// Method to add three integers</span>
    <span class="key">public</span> <span class="key">int</span> <span style="background:#f2f19d;">Add(<span class="key">int</span> a, <span class="key">int</span> b, <span class="key">int</span> c)</span>
    {
        <span class="key">return</span> a + c + c;
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        MathOperations math = <span class="key">new</span> MathOperations();

        Console.WriteLine(math.Add(1, 2));        <span class="com">// Output: 3</span>
        Console.WriteLine(math.Add(1, 2, 3));     <span class="com">// Output: 6</span>
    }
} </code></pre>

<div style="padding: 0.3125rem 0.3125rem 0.625rem 0.625rem;">
	<p class="custp1 p-mb-0">The <b>MathOperations</b> class has two <b>Add</b> methods with different parameters. The correct method is chosen at compile-time based on the arguments provided.</p>
</div>
</div>

<br><br>

<li><strong>Run-time Polymorphism:</strong> Also called as <strong>Dynamic Polymorphism/ Method Overriding/ Late Binding</strong>. It Allows a subclass to provide a specific implementation of a method that is already defined in its superclass. Achieved through method overriding, typically using inheritance and interfaces.</li>
<button class="shbtn" id="shbtn36713" onclick="showHideBlock(36713)">&#9660; <u>Show example</u></button>
<div id="shdiv36713" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">class</span> Animal
{
    <span class="com">// Virtual method</span>
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">virtual</span> <span class="key">void</span> <span style="background:#f2f19d;">MakeSound()</span>
    {
        Console.WriteLine(<span class="str">"Some generic animal sound"</span>);
    }
}

<span class="key">class</span> Dog : Animal
{
    <span class="com">// Overriding the virtual method</span>
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">override</span> <span class="key">void</span> <span style="background:#f2f19d;">MakeSound()</span>
    {
        Console.WriteLine(<span class="str">"Bark"</span>);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        Animal myAnimal;

        myAnimal = <span class="key">new</span> Dog();
        myAnimal.MakeSound();  <span class="com">// Output: Bark</span>
    }
} </code></pre>

<div style="padding: 0.3125rem 0.3125rem 0.625rem 0.625rem;">
	<p class="custp1 p-mb-0">The <b>Animal</b> class has a virtual method <b>MakeSound</b>. The <b>Dog</b> class override the MakeSound method to provide specific implementations. At runtime, the appropriate method is called based on the object type.</p>
</div>

</div>
</ol>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can method overloading have different return type in C#?</strong></h3>



<p class="custp1 p-mb-0">If both methods have the same parameter types, but different return type, then it is not possible. you cannot declare two methods with the same signature and different return type.</p>



<p class="custp1 p-mb-0">Method overloading primarily depends on having different parameter lists (different number or types of parameters). <strong>The parameter lists must differ</strong>, then you can have method overloading with different return type, see the below example.</p>



<button class="shbtn" id="shbtn9736" onclick="showHideBlock(9736)">&#9660; <u>Show example</u></button>
<div id="shdiv9736" style="display: none;" class="shdt">
<br>
<div style="padding-left: 0.625rem;"><b><span style="color:red;">&#10006;</span> <u>Invalid Overloading with different return type &#8211; Example</u></b></div>
<pre class="pchl"><code><span class="com">// Method with int return type</span>
<span class="key">public</span> <span class="key">int</span> Add(<span class="key">int</span> a, <span class="key">int</span> b)
{
	<span class="key">return</span> a + b;
}

<span class="com">// Method with double return type</span>
<span style="color:red;">// This will cause a compilation error because the parameter list is the same</span>
<span class="key">public</span> <span class="key" style="background:#f2f19d;">double</span> Add(<span style="background:#f2f19d;"><span class="key">int</span> a, <span class="key">int</span> b</span>)
{
	<span class="key">return</span> a + b;
} </code></pre>

<br><br>
<div style="padding-left: 0.625rem;"><b><span style="color:green;">&#10004;</span> <u>Valid Overloading with different return type &#8211; Example</u></b></div>
<pre class="pchl"><code><span class="com">// Method to add two integers</span>
<span class="key">public</span> <span class="key">int</span> Add(<span class="key">int</span> a, <span class="key">int</span> b)
{
	<span class="key">return</span> a + b;
}

<span class="com">// Method to add two doubles</span>
<span class="com">/* different number or types of parameters */</span>
<span class="key">public</span> <span class="key" style="background:#f2f19d;">double</span> Add(<span style="background:#f2f19d;"><span class="key">double</span> a, <span class="key">double</span> b</span>)
{
	<span class="key">return</span> a + b;
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can static methods be overloaded in C#?</strong></h3>



<p class="custp1 p-mb-0">Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can return type be different in method overriding C#?</strong></h3>



<p class="custp1 p-mb-0">An <span class="spanHT">override</span> method must have the same signature as the overridden base method. <span class="spanHT">override</span> methods support covariant return types. In particular, the return type of an <span class="spanHT">override</span> method can derive from the return type of the corresponding base method.</p>



<p class="custp1 p-mb-0">You cannot override a non-virtual or static method. The overridden base method must be <span class="spanHT">virtual</span>, <span class="spanHT">abstract</span>, or <span class="spanHT">override</span>.</p>



<p class="custp1 p-mb-0">An <span class="spanHT">override</span> declaration cannot change the accessibility of the <span class="spanHT">virtual</span> method. Both the <span class="spanHT">override</span> method and the <span class="spanHT">virtual</span> method must have the same access level modifier.</p>



<p class="custp1 p-mb-0">You cannot use the <span class="spanHT">new</span>, <span class="spanHT">static</span>, or <span class="spanHT">virtual</span> modifiers to modify an <span class="spanHT">override</span> method.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is an Abstract class?</strong></h3>



<p class="custp1 p-mb-0">An abstract class is a class that cannot be instantiated and is meant to be inherited by other classes. It can contain abstract methods (without implementation) and regular methods (with implementation).</p>



<button class="shbtn" id="shbtn19704" onclick="showHideBlock(19704)">&#9660; <u>Show example</u></button>
<div id="shdiv19704" style="display: none;">
<pre class="pchl"><code><span class="com">// Abstract class</span>
<span style="background:#f2f19d;"><span class="key">abstract</span> <span class="key">class</span></span> Demo1
{
    <span class="com">// Abstract method (no implementation)</span>
    <span style="background:#f2f19d;"><span class="key">public</span> <span class="key"><b>abstract</b></span> <span class="key">void</span> Method1()</span>;

    <span class="com">// Regular method</span>
    <span class="key">public</span> <span class="key">void</span> Method2()
    {
        <span class="com">// Implementation.....</span>
    }
}

<span class="com">// Derived class</span>
<span class="key">class</span> Demo2 : Demo1
{
    <span class="com">// Providing implementation for the abstract method</span>
    <span style="background:#f2f19d;"><span class="key">public</span> <span class="key"><b>override</b></span> <span class="key">void</span> Method1()</span>
    {
        <span class="com">// Implementation.....</span>
    }
} </code></pre>
</span>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>Can I declare an abstract class without defining an abstract method in it?</strong></strong></h3>



<p class="custp1 p-mb-0">Yes, you can have an abstract class without any abstract methods. An abstract class can contain only regular methods (with implementation), properties, fields, and other members. The purpose of an abstract class in such cases is to prevent instantiation of the class directly and to provide a common base for derived classes.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is an Abstract method?</strong></h3>



<p class="custp1 p-mb-0">An abstract method is a method that is declared in an abstract class but does not have an implementation in that class.</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>Abstract methods contain only the method signature (name, return type, parameters) without any body.</li>



<li>They can only be declared in abstract classes.</li>



<li>Any non-abstract class inheriting an abstract class must implement all its abstract methods, ensuring that they provide specific functionality.</li>



<li>Abstract classes, and therefore their abstract methods, cannot be instantiated directly.</li>
</ul>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can I declare &#8220;abstract method&#8221; in a &#8220;non-abstract class&#8221;?</strong></h3>



<p class="custp1 p-mb-0">No, you cannot declare an abstract method in a non-abstract class. Abstract methods can only be declared in abstract classes. This is because an abstract method does not have an implementation, and a non-abstract class is expected to be instantiable and provide full implementations for all its methods.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Interface?</strong></h3>



<p class="custp1 p-mb-0">An interface class is a blueprint for classes that defines methods and properties but does not provide their implementation. Classes that implement the interface must provide the implementation for all its members.</p>



<button class="shbtn" id="shbtn59499" onclick="showHideBlock(59499)">&#9660; <u>Show example</u></button>
<div id="shdiv59499" style="display: none;">
<pre class="pchl"><code><span class="com">// Define an interface</span>
<span style="background:#f2f19d;"><span class="key">interface</span> IAnimal</span>
{
    <span class="com">// Interface method (no implementation)</span>
    <span class="key">void</span> MakeSound();
    <span class="key">void</span> Sleep();
}

<span class="com">// Implement the interface in a class</span>
<span class="key">class</span> Dog : <span style="background:#f2f19d;">IAnimal</span>
{
    <span class="com">// Providing implementation for the interface methods</span>
    <span class="key">public</span> <span class="key">void</span> MakeSound()
    {
        Console.WriteLine(<span class="str">"Bark"</span>);
    }

    <span class="key">public</span> <span class="key">void</span> Sleep()
    {
        Console.WriteLine(<span class="str">"Sleeping..."</span>);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        Dog myDog = <span class="key">new</span> Dog();
        myDog.MakeSound();  <span class="com">// Output: Bark</span>
        myDog.Sleep();      <span class="com">// Output: Sleeping...</span>
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>Can Interface have accessibility modifier</strong>?</strong></h3>



<p class="custp1 p-mb-0">All elements in the Interface should be public. Therefore, by default, all interface elements are <span class="spanHT">public</span> by default.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can a class implement multiple Interfaces?</strong></h3>



<p class="custp1 p-mb-0">Yes, a class can implement multiple interfaces. This allows a class to inherit behaviors and contracts from more than one interface.</p>



<button class="shbtn" id="shbtn17871" onclick="showHideBlock(17871)">&#9660; <u>Show example</u></button>
<div id="shdiv17871" style="display: none;">
<pre class="pchl"><code>
<span class="com">// First interface</span>
<span class="key">interface</span> IWalkable
{
    <span class="key">void</span> Walk();
}

<span class="com">// Second interface</span>
<span class="key">interface</span> IRunnable
{
    <span class="key">void</span> Run();
}

<span class="com">// Class implementing both interfaces</span>
<span class="key">class</span> Person <span style="background:#f2f19d;">: IWalkable, IRunnable</span>
{
    <span class="key">public</span> <span class="key">void</span> Walk()
    {
        Console.WriteLine(<span class="str">"Person is walking."</span>);
    }

    <span class="key">public</span> <span class="key">void</span> Run()
    {
        Console.WriteLine(<span class="str">"Person is running."</span>);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        Person person = <span class="key">new</span> Person();
        person.Walk();  <span class="com">// Output: Person is walking.</span>
        person.Run();   <span class="com">// Output: Person is running.</span>
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference between Abstract and Interface.</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th></th>
            <th>Abstract Class</th>
            <th>Interface</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Keyword</th>
            <td>abstract</td>
            <td>interface</td>
        </tr>
        <tr>
            <th>Methods</th>
            <td>Can have both abstract (without implementation) and regular (with implementation) methods</td>
            <td>Can only have methods without implementation (<a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods" target="_blank" rel="noopener">default methods with implementations are allowed from C# 8.0</a>)</td>
        </tr>
        <tr>
            <th>Fields</th>
            <td>Can have fields (variables)</td>
            <td>Cannot have fields</td>
        </tr>
        <tr>
            <th>Properties</th>
            <td>Can have properties with or without implementation</td>
            <td>Can have properties but no implementation</td>
        </tr>
        <tr>
            <th>Constructors</th>
            <td>Can have constructors</td>
            <td>Cannot have constructors</td>
        </tr>
        <tr>
            <th>Inheritance</th>
            <td>Can inherit from only one base class</td>
            <td>Can inherit from multiple interfaces</td>
        </tr>
        <tr>
            <th>Access Modifiers</th>
            <td>Can use access modifiers (public, protected, private)</td>
            <td>Members are public by default, no access modifiers allowed</td>
        </tr>
        <tr>
            <th>Usage</th>
            <td>Used when classes share a common base with some shared implementation</td>
            <td>Used to define a contract that multiple classes can implement</td>
        </tr>
        <tr>
            <th>Instantiation</th>
            <td>Cannot be instantiated directly</td>
            <td>Cannot be instantiated directly</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a Constructor?</strong></h3>



<p class="custp1 p-mb-0">A constructor is a special method in a class that is automatically called when an object of the class is created. It is used to initialize the object&#8217;s properties.</p>



<p class="custp1 p-mb-0">A constructor must have the same name as the class and cannot have a return type, not even <span class="spanHT">void</span>.</p>



<button class="shbtn" id="shbtn51702" onclick="showHideBlock(51702)">&#9660; <u>Show example</u></button>
<div id="shdiv51702" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> Person
{
    <span class="com">// Default constructor</span>
    <span style="background:#f2f19d;"><span class="key">public</span> Person()</span>
    {}
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can I have multiple Constructors in a Class?</strong></h3>



<p class="custp1 p-mb-0">Yes, you can have multiple constructors in a class. This is known as constructor overloading, where each constructor has a different parameter list (different number or types of parameters).</p>



<button class="shbtn" id="shbtn83739" onclick="showHideBlock(83739)">&#9660; <u>Show example</u></button>
<div id="shdiv83739" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> Person
{
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> <span class="key">int</span> Age { get; set; }

    <span class="com">// Default constructor</span>
    <span style="background:#f2f19d;"><span class="key">public</span> Person()</span>
    {
        Name = <span class="str">"Unknown"</span>;
        Age = 0;
    }

    <span class="com">// Constructor with one parameter</span>
    <span style="background:#f2f19d;"><span class="key">public</span> Person(<span class="key">string</span> name)</span>
    {
        Name = name;
        Age = 0;
    }

    <span class="com">// Constructor with two parameters</span>
    <span style="background:#f2f19d;"><span class="key">public</span> Person(<span class="key">string</span> name, <span class="key">int</span> age)</span>
    {
        Name = name;
        Age = age;
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        Person person1 = <span class="key">new</span> Person();
        Person person2 = <span class="key">new</span> Person(<span class="str">"Alice"</span>);
        Person person3 = <span class="key">new</span> Person(<span class="str">"Bob"</span>, 25);

        Console.WriteLine($<span class="str">"{person1.Name}, {person1.Age}"</span>); <span class="com">// Output: Unknown, 0</span>
        Console.WriteLine($<span class="str">"{person2.Name}, {person2.Age}"</span>); <span class="com">// Output: Alice, 0</span>
        Console.WriteLine($<span class="str">"{person3.Name}, {person3.Age}"</span>); <span class="com">// Output: Bob, 25</span>
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of a constructor?</strong></h3>



<p class="custp1 p-mb-0">The purpose of a constructor is to initialize a new object of a class.</p>



<p class="custp1 p-mb-0"><em><strong>Key Points:</strong></em></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Initialization</strong>: Sets initial values for the object&#8217;s properties.</li>



<li><strong>Setup</strong>: Performs any necessary setup tasks for the object.</li>



<li><strong>No Return Type</strong>: Constructors do not have a return type, not even <span class="spanHT">void</span>.</li>



<li><strong>Same Name as Class</strong>: Constructors must have the same name as the class.</li>
</ul>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the types of constructors in OOP?</strong></h3>



<p class="custp1 p-mb-0">There are several types of constructors &#8211; Default, Parameterized, Copy, Static, Private:</p>



<ol class="ol1 ol1-mb-0">
<li class="custp1"><b>Default Constructor:</b> A constructor that takes no parameters. It initializes objects with default values.</li>
<button class="shbtn" id="shbtn38955" onclick="showHideBlock(38955)">&#9660; <u>Show example</u></button>
<div id="shdiv38955" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> Person
{
    <span class="com"><b>// Default constructor</b></span>
    <span class="key">public</span> <span style="background:#f2f19d;">Person()</span>
    {
        <span class="com">// your code</span>
    }
} </code></pre>
</div>

<li class="custp1"><b>Parameterized Constructor:</b> A constructor that takes parameters to initialize objects with specific values.</li>
<button class="shbtn" id="shbtn53972" onclick="showHideBlock(53972)">&#9660; <u>Show example</u></button>
<div id="shdiv53972" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> Person
{
    <span class="com"><b>// Parameterized constructor</b></span>
    <span class="key">public</span> <span style="background:#f2f19d;">Person(<span class="key">string</span> name, <span class="key">int</span> age)</span>
    {
        <span class="com">// your code</span>
    }
} </code></pre>
</div>

<li class="custp1"><b>Copy Constructor:</b> A constructor that creates a new object as a copy of an existing object. C# does not have a built-in copy constructor, but you can implement one.</li>
<button class="shbtn" id="shbtn73582" onclick="showHideBlock(73582)">&#9660; <u>Show example</u></button>
<div id="shdiv73582" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> Person
{
    <span class="com"><b>// Copy constructor</b></span>
    <span class="key">public</span> <span style="background:#f2f19d;">Person(<b>Person</b> person)</span>
    {
        <span class="com">// your code</span>
    }
} </code></pre>
</div>

<li class="custp1"><b>Static Constructor:</b> A constructor used to initialize static members of the class. It is called once, before any instance of the class is created or any static member is accessed.</li>
<button class="shbtn" id="shbtn17486" onclick="showHideBlock(17486)">&#9660; <u>Show example</u></button>
<div id="shdiv17486" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> Person
{
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">static</span> <span class="key">int</span> Population;

    <span class="com"><b>// Static constructor</b></span>
    <span style="background:#f2f19d;"><span class="key">static</span> Person()</span>
    {
        Population = 0;
    }

    <span class="com">// Instance constructor</span>
    <span class="key">public</span> Person()
    {
        Population++;
    }
} </code></pre>
</div>

<li class="custp1"><b>Private Constructor:</b> A constructor that cannot be accessed outside its class. It is used to prevent the creation of instances from outside the class, often used in singleton pattern.</li>
<button class="shbtn" id="shbtn10082" onclick="showHideBlock(10082)">&#9660; <u>Show example</u></button>
<div id="shdiv10082" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> Singleton
{
    <span class="key">private</span> <span class="key" style="background:#f2f19d;">static</span> Singleton instance = null;

    <span class="com"><b>// Private constructor</b></span>
    <span style="background:#f2f19d;"><span class="key">private</span> Singleton() { }</span>

    <span class="key">public</span> <span class="key" style="background:#f2f19d;">static</span> Singleton Instance
    {
        <span class="key">get</span>
        {
            <span class="key">if</span> (instance == <span class="key">null</span>)
            {
                instance = <span class="key">new</span> Singleton();
            }
            <span class="key">return</span> instance;
        }
    }
} </code></pre>
</div>

</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can constructors be overloaded?</strong></h3>



<p class="custp1 p-mb-0">Yes</p>



<button class="shbtn" id="shbtn72912" onclick="showHideBlock(72912)">&#9660; <u>Show example</u></button>
<div id="shdiv72912" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> Person
{
    <span class="com">// Default constructor</span>
    <span class="key">public</span> Person<span style="background:#f2f19d;">()</span> {}

    <span class="com">// Constructor with one parameter</span>
    <span class="key">public</span> Person<span style="background:#f2f19d;">(<span class="key">string</span> name)</span> {}

    <span class="com">// Constructor with two parameters</span>
    <span class="key">public</span> Person<span style="background:#f2f19d;">(<span class="key">string</span> name, <span class="key">int</span> age)</span> {}
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between a constructor and a method?</strong></h3>



<br><table>
    <thead>
        <tr>
            <th></th>
            <th>Constructor</th>
            <th>Method</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Purpose</th>
            <td>Initializes a new object</td>
            <td>Performs an action or calculates a value</td>
        </tr>
        <tr>
            <th>Name</th>
            <td>Same name as the class</td>
            <td>Can have any name</td>
        </tr>
        <tr>
            <th>Return Type</th>
            <td>No return type, not even void</td>
            <td>Must have a return type, or void if no value is returned</td>
        </tr>
        <tr>
            <th>Call</th>
            <td>Automatically called when an object is created</td>
            <td>Explicitly called using the object reference</td>
        </tr>
        <tr>
            <th>Overloading</th>
            <td>Can be overloaded</td>
            <td>Can be overloaded</td>
        </tr>
        <tr>
            <th>Inheritance</th>
            <td>Not inherited by derived classes, but can be called explicitly</td>
            <td>Inherited by derived classes</td>
        </tr>
        <tr>
            <th>Usage</th>
            <td>Sets up initial state of an object</td>
            <td>Defines behaviors and functionalities</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Destructor in OOPs?</strong></h3>



<p class="custp1 p-mb-0">A destructor in Object-Oriented Programming (OOP) is a special member function of a class that is executed when an object of that class is destroyed. Destructors are used to perform any necessary final clean-up when an object is no longer needed, such as releasing resources like memory, file handles, or network connections and to perform any finalization steps required before the object is destroyed.</p>



<p class="custp1 p-mb-0">In <strong>C#</strong>, destructors are defined using a tilde <span class="spanHT">(~)</span> followed by the class name. The .NET garbage collector automatically calls the destructor before reclaiming the memory used by an object. </p>



<p class="custp1 p-mb-0"><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"><strong>Note:</strong></mark> Using <span class="spanHT">IDisposable</span> and <span class="spanHT">using</span> is often a better practice for resource management in C#.</p>



<button class="shbtn" id="shbtn13919" onclick="showHideBlock(13919)">&#9660; <u>Show example</u></button>
<div id="shdiv13919" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> ResourceHolder
{
    <span class="com">// Constructor</span>
    <span class="key">public</span> ResourceHolder()
    {
        <span class="com">// Acquire resources</span>
        Console.WriteLine(<span class="str">"Resource acquired."</span>);
    }

    <span class="com">// Destructor</span>
    <span style="background:#f2f19d;">~ResourceHolder()</span>
    {
        <span class="com">// Release resources</span>
        Console.WriteLine(<span class="str">"Resource released."</span>);
    }

    <span class="key">public</span> <span class="key">void</span> DoWork()
    {
        Console.WriteLine(<span class="str">"Working..."</span>);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        ResourceHolder rh = <span class="key">new</span> ResourceHolder();
        rh.DoWork();
        
        <span class="com">// ResourceHolder object will be cleaned up when it goes out of scope</span>
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the significance of the super keyword in inheritance?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">super</span> keyword is significant in inheritance because it allows a derived class to access and invoke methods, properties, and constructors of its base class. This is particularly important for ensuring proper initialization and extending or modifying the behavior of base class methods in derived classes. </p>



<p class="custp1 p-mb-0">Although C# does not have a <span class="spanHT">super</span> keyword, the <span class="spanHT"><strong>base</strong></span> keyword serves the same purpose.</p>



<button class="shbtn" id="shbtn14533" onclick="showHideBlock(14533)">&#9660; <u>Show example</u></button>
<div id="shdiv14533" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> Animal
{
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }

    <span class="key">public</span> Animal(<span class="key">string</span> name)
    {
        Name = name;
    }

    <span class="key">public</span> <span class="key">virtual</span> <span class="key">void</span> MakeSound()
    {
        Console.WriteLine(<span class="str">"Animal sound"</span>);
    }
}

<span class="key">class</span> Dog : Animal
{
    <span class="key">public</span> Dog(<span class="key">string</span> name) <span style="background:#f2f19d;">: <span class="key">base</span>(name)</span> <span class="com">// Calling the base class constructor</span>
    {
    }

    <span class="key">public</span> <span class="key">override</span> <span class="key">void</span> MakeSound()
    {
        <span style="background:#f2f19d;">base.MakeSound()</span>; <span class="com">// Calling the base class method</span>
        Console.WriteLine(<span class="str">"Dog barks"</span>);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        Dog dog = <span class="key">new</span> Dog(<span class="str">"Buddy"</span>);
        dog.MakeSound(); <span class="com">// Output: Animal sound</span>
                         <span class="com">//         Dog barks</span>
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Explain the &#8220;this&#8221; keyword.</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">&#8216;this&#8217;</span> keyword refers to the current instance of the class in which it is used and provides a way to reference the current object.</p>



<p class="custp1 p-mb-0"><em><strong>Key Uses of <span class="spanHT">this</span> Keyword:</strong></em></p>



<ol class="ol1-mb-0 wp-block-list">
<li><strong>Distinguishing Between Instance Variables and Parameters</strong>: When a parameter or a local variable has the same name as an instance variable, <span class="spanHT">this</span> can be used to refer to the instance variable.</li>



<li><strong>Calling Other Constructors</strong>: It can be used to call another constructor in the same class.</li>



<li><strong>Passing the Current Instance</strong>: It can be used to pass the current object as a parameter to other methods.</li>



<li><strong>Returning the Current Instance</strong>: It can be used to return the current object from a method.</li>
</ol>



<button class="shbtn" id="shbtn56497" onclick="showHideBlock(56497)">&#9660; <u>Show example</u></button>
<div id="shdiv56497" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> Person
{
    <span class="key">private</span> <span class="key">string</span> name;
    <span class="key">private</span> <span class="key">int</span> age;

    <span class="com">// Constructor</span>
    <span class="key">public</span> Person(<span class="key">string</span> name, <span class="key">int</span> age)
    {
        <span class="com">// Using 'this' to distinguish between the instance variable and the parameter</span>
        this.name = name;
        this.age = age;
    }

    <span class="com">// Method to set the name</span>
    <span class="key">public</span> <span class="key">void</span> SetName(<span class="key">string</span> name)
    {
        <span class="com">// Using 'this' to refer to the instance variable</span>
        this.name = name;
    }

    <span class="com">// Method to display information</span>
    <span class="key">public</span> <span class="key">void</span> DisplayInfo()
    {
        <span class="com">// Using 'this' is optional here, as there's no ambiguity</span>
        Console.WriteLine($<span class="str">"Name: {this.name}, Age: {this.age}"</span>);
    }

    <span class="com">// Constructor chaining using 'this'</span>
    <span class="key">public</span> Person() : <span class="key">this</span>(<span class="str">"Unknown"</span>, 0)
    {
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="com">// Creating an object using the parameterized constructor</span>
        Person person1 = <span class="key">new</span> Person(<span class="str">"Alice"</span>, 30);
        person1.DisplayInfo(); <span class="com">// Output: Name: Alice, Age: 30</span>

        <span class="com">// Creating an object using the default constructor</span>
        Person person2 = <span class="key">new</span> Person();
        person2.DisplayInfo(); <span class="com">// Output: Name: Unknown, Age: 0</span>

        <span class="com">// Using the SetName method</span>
        person2.SetName(<span class="str">"Bob"</span>);
        person2.DisplayInfo(); <span class="com">// Output: Name: Bob, Age: 0</span>
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Data Types? </strong></h3>



<p class="custp1 p-mb-0">defines the structure, behavior, and capabilities of data, specifying the operations that can be performed and how the data is stored.</p>



<p class="custp1"><strong><em>Different Kind of &#8220;Types&#8221;</em></strong> &#8211; Value Type, Reference Type, User-Defined Type, Abstract Type, Primitive Type, Composite Type.</p>



<ol class="ol1 ol1-mb-0">

<li><b>Value Types:</b> Types that store actual data directly. Examples: <b>int</b>, <b>float</b>, <b>struct</b> in C#.</li>
<button class="shbtn" id="shbtn63273" onclick="showHideBlock(63273)">&#9660; <u>Show example</u></button>
<div id="shdiv63273" style="display: none;">
<pre class="pchl"><code><span class="com">// Value Type (struct)</span>
<span class="key">struct</span> ExampleStruct
{
    <span class="key">public</span> <span class="key">int</span> Value;
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="com">// Value Type</span>
        ExampleStruct struct1 = <span class="key">new</span> ExampleStruct();
        struct1.Value = 10;
        ExampleStruct struct2 = struct1;
        struct2.Value = 20;
        Console.WriteLine(struct1.Value); <span class="com">// Output: 10</span>
    }
} </code></pre>
</div>
<br>

<li class="custp1"><b>Reference Types:</b> Types that store references (addresses) to the actual data rather than the data itself. Examples: <b>Classes</b>, <b>arrays</b>, <b>strings</b> in C#.</li>
<button class="shbtn" id="shbtn59376" onclick="showHideBlock(59376)">&#9660; <u>Show example</u></button>
<div id="shdiv59376" style="display: none;">
<pre class="pchl"><code><span class="com">// Reference Type (class)</span>
<span class="key">class</span> ExampleClass
{
    <span class="key">public</span> <span class="key">int</span> Value;
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="com">// Reference Type</span>
        ExampleClass obj1 = <span class="key">new</span> ExampleClass();
        obj1.Value = 10;
        ExampleClass obj2 = obj1;
        obj2.Value = 20;
        Console.WriteLine(obj1.Value); <span class="com">// Output: 20</span>
    }
} </code></pre>
</div>
<br>


<li class="custp1"><b>User-Defined Types:</b> Types that are defined by the user using the language’s class and struct mechanisms. Examples: Custom classes and structs.</li>

<li class="custp1"><b>Abstract Types:</b> Types that cannot be instantiated directly and are meant to be inherited by other classes. Examples: Abstract classes and interfaces.</li>

<li class="custp1"><b>Primitive Types:</b> Basic data types provided by a programming language. Examples: int, char, float, double, boolean in languages like Java and C#.</li>

<li class="custp1"><b>Composite Types:</b> Also known as complex types, they are composed of multiple primitive types. Examples: Arrays, structures, and classes.</li>

</ol>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference between &#8220;Class&#8221; and &#8220;Struct&#8221; in OOPs.</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th>Class</th>
            <th>Struct (Structure)</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Reference type</td>
            <td>Value type</td>
        </tr>
        <tr>
            <td>Allocated on the heap</td>
            <td>Allocated on the stack</td>
        </tr>
        <tr>
            <td>Has a default constructor</td>
            <td>No default constructor</td>
        </tr>
        <tr>
            <td>Supports inheritance</td>
            <td>Does not support inheritance</td>
        </tr>
        <tr>
            <td>Can implement interfaces</td>
            <td>Can implement interfaces</td>
        </tr>
        <tr>
            <td>Can have abstract members</td>
            <td>Cannot have abstract members</td>
        </tr>
        <tr>
            <td>Can be null</td>
            <td>Cannot be null (unless using nullable types)</td>
        </tr>
        <tr>
            <td>Generally slower to access due to heap allocation</td>
            <td>Generally faster to access due to stack allocation</td>
        </tr>
        <tr>
            <td>Used for complex data structures and behavior</td>
            <td>Used for small, simple data structures</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Access modifiers/ specifiers?</strong></h3>



<p class="custp1 p-mb-0">Access modifiers/ specifiers are keywords to define the visibility and accessibility of classes, methods, and other members. They control how the members of a class can be accessed from other parts of the code.</p>



<p class="custp1"><strong>Access Modifiers</strong> &#8211; <span class="spanHT">Public</span>, <span class="spanHT">Private</span>, <span class="spanHT">Protected</span>, <span class="spanHT">Internal</span>, <span class="spanHT">Protected Internal</span>, <span class="spanHT">Private Protected</span></p>



<ol class="ol1 ol1-mb-0">

<li><b>Public:</b> Members declared as public are accessible from any other code in the same assembly or another assembly that references it.</li>
<button class="shbtn" id="shbtn41619" onclick="showHideBlock(41619)">&#9660; <u>Show example</u></button>
<div id="shdiv41619" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> MyClass
{
    <span class="key">public</span> <span class="key">int</span> MyField; <span class="com">// Accessible from anywhere</span>
} </code></pre>
</div>


<br><br>
<li><b>Private:</b> Members declared as private are accessible only within the same class or struct.</li>
<button class="shbtn" id="shbtn34030" onclick="showHideBlock(34030)">&#9660; <u>Show example</u></button>
<div id="shdiv34030" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> MyClass
{
    <span class="key">private</span> <span class="key">int</span> MyField; <span class="com">// Accessible only within MyClass</span>
} </code></pre>
</div>


<br><br>
<li><b>Protected:</b> Members declared as protected are accessible within the same class and by derived class instances.</li>
<button class="shbtn" id="shbtn73775" onclick="showHideBlock(73775)">&#9660; <u>Show example</u></button>
<div id="shdiv73775" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> MyBaseClass
{
    <span class="key">protected</span> <span class="key">int</span> MyField; <span class="com">// Accessible within MyBaseClass and derived classes</span>
}

<span class="key">public</span> <span class="key">class</span> MyDerivedClass : MyBaseClass
{
    <span class="key">void</span> MyMethod()
    {
        MyField = 10; <span class="com">// Accessible here</span>
    }
} </code></pre>
</div>


<br><br>
<li><b>Internal:</b> Members declared as internal are accessible only within the same assembly, but not from another assembly.</li>
<button class="shbtn" id="shbtn53951" onclick="showHideBlock(53951)">&#9660; <u>Show example</u></button>
<div id="shdiv53951" style="display: none;">
<pre class="pchl"><code><span class="key">internal</span> <span class="key">class</span> MyClass
{
    <span class="key">internal</span> <span class="key">int</span> MyField; <span class="com">// Accessible within the same assembly</span>
} </code></pre>
</div>


<br><br>
<li><b>Protected Internal:</b> Members declared as protected internal are accessible within the same assembly or from derived classes in other assemblies.</li>
<button class="shbtn" id="shbtn45023" onclick="showHideBlock(45023)">&#9660; <u>Show example</u></button>
<div id="shdiv45023" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="com">// <b>Assembly1:</b> Library</span>
<span class="key">namespace</span> Library
{
    <span class="key">public</span> <span class="key">class</span> BaseClass
    {
        <span class="key">protected</span> <span class="key">internal</span> <span class="key">int</span> protectedInternalField;

        <span class="key">public</span> BaseClass()
        {
            protectedInternalField = 10;
        }

        <span class="key">protected</span> <span class="key">internal</span> <span class="key">void</span> ProtectedInternalMethod()
        {
            Console.WriteLine(<span class="str">"Protected Internal Method"</span>);
        }
    }
} </code></pre>
<br>
<pre class="pchl"><code><span class="com">// <b>Assembly2</b>: Application</span>
<span class="key">using</span> Library;
<span class="key">using</span> System;

<span class="key">namespace</span> Application
{
    <span class="key">public</span> <span class="key">class</span> DerivedClass : BaseClass
    {
        <span class="key">public</span> <span class="key">void</span> AccessProtectedInternalMembers()
        {
            <span class="com">// Accessing protected internal member from base class</span>
            Console.WriteLine($<span class="str">"Protected Internal Field: {protectedInternalField}"</span>);
            ProtectedInternalMethod();
        }
    }

    <span class="key">class</span> Program
    {
        <span class="key">static</span> <span class="key">void</span> Main(string[] args)
        {
            DerivedClass obj = <span class="key">new</span> DerivedClass();
            obj.AccessProtectedInternalMembers();

            <span class="com">// Accessing protected internal member directly from an instance of the base class</span>
            BaseClass baseObj = <span class="key">new</span> BaseClass();
            baseObj.protectedInternalField = 20; <span class="com">// Error: Inaccessible due to its protection level</span>
            baseObj.ProtectedInternalMethod(); <span class="com">// Error: Inaccessible due to its protection level</span>
        }
    }
} </code></pre>
</div>


<br><br>
<li><b>Private Protected:</b> Members declared as private protected are accessible within the same class and derived classes within the same assembly.</li>
<button class="shbtn" id="shbtn81327" onclick="showHideBlock(81327)">&#9660; <u>Show example</u></button>
<div id="shdiv81327" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> MyBaseClass
{
    <span class="key">private</span> <span class="key">protected</span> <span class="key">int</span> MyField; <span class="com">// Accessible within MyBaseClass and derived classes in the same assembly</span>
}

<span class="key">public</span> <span class="key">class</span> MyDerivedClass : MyBaseClass
{
    <span class="key">void</span> MyMethod()
    {
        MyField = 10; <span class="com">// Accessible here</span>
    }
} </code></pre>
</div>


</ol>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>What is the ‘override’ keyword used for?</strong></strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">override</span> keyword in C# is used for the following purposes:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Extending or Modifying Base Class Methods</strong>: Allows a derived class to provide a specific implementation of a method that is already defined in its base class.</li>



<li><strong>Implementing Polymorphism</strong>: Enables runtime polymorphism, allowing the derived class method to be called through a base class reference.</li>



<li><strong>Overriding Virtual/Abstract Methods</strong>: Used to override methods marked as <span class="spanHT">virtual</span>, <span class="spanHT">abstract</span>, or <span class="spanHT">override</span> in the base class.</li>



<li><strong>Ensuring Derived Class Method Execution</strong>: Guarantees that the derived class&#8217;s version of the method is executed, even when called through a base class reference.</li>



<li><strong>Providing Specific Functionality</strong>: Allows derived classes to implement or modify behavior specific to their needs, providing more tailored functionality.</li>
</ul>



<button class="shbtn" id="shbtn35035" onclick="showHideBlock(35035)">&#9660; <u>Show example</u></button>
<div id="shdiv35035" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> BaseClass
{
    <span class="key">public</span> <span class="key">virtual</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(<span class="str">"Display method in BaseClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> DerivedClass : BaseClass
{
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">override</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(<span class="str">"Display method in DerivedClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        BaseClass obj = <span class="key">new</span> DerivedClass();
        obj.Display();  <span class="com">// Output: Display method in DerivedClass</span>
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can I override a method that is marked as &#8216;override&#8217; in a base class?</strong></h3>



<p class="custp1 p-mb-0">Yes</p>



<button class="shbtn" id="shbtn30647" onclick="showHideBlock(30647)">&#9660; <u>Show example</u></button>
<div id="shdiv30647" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> BaseClass
{
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">virtual</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(<span class="str">"Display method in BaseClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> DerivedClass : BaseClass
{
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">override</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(<span class="str">"Display method in DerivedClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> FurtherDerivedClass : DerivedClass
{
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">override</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(<span class="str">"Display method in FurtherDerivedClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        BaseClass obj = <span class="key">new</span> FurtherDerivedClass();
        obj.Display();  <span class="com">// Output: Display method in FurtherDerivedClass</span>
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Sealed Class and Sealed methods in OOPs</strong></h3>



<p class="custp1">A sealed class and sealed methods are used to restrict inheritance and prevent further derivation or overriding. This can be useful for ensuring that a class or method&#8217;s behavior remains unchanged. This is done by <span class="spanHT">sealed</span> keyword.</p>



<p class="p-mb-0"><strong>1) Sealed Class &#8211;</strong> A sealed class is a class that cannot be inherited by any other class. This means you cannot create a subclass of a sealed class. It is used to prevent further inheritance and to secure the implementation of a class.</p>



<button class="shbtn" id="shbtn93055" onclick="showHideBlock(93055)">&#9660; <u>Show example</u></button>
<div id="shdiv93055" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">public</span> <span class="key" style="background:#f2f19d;">sealed</span> <span class="key">class</span> SealedClass
{
    <span class="key">public</span> <span class="key">void</span> DisplayMessage()
    {
        Console.WriteLine(<span class="str">"This is a sealed class."</span>);
    }
}

<div style="background-color:#ffb6c154"><span style="color:red">// The following code will result in a compilation error because SealedClass is sealed</span>
public class DerivedClass <b>: SealedClass</b></span>
{
}
</div>

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        SealedClass sealedClass = <span class="key">new</span> SealedClass();
        sealedClass.DisplayMessage();
    }
} </code></pre>
</div>
<br><br>



<p class="custp1 p-mb-0"><strong>2) Sealed Method &#8211;</strong> A sealed method is a method in a derived class that overrides a method in a base class but cannot be further overridden by any classes that derive from the derived class.</p>



<button class="shbtn" id="shbtn29115" onclick="showHideBlock(29115)">&#9660; <u>Show example</u></button>
<div id="shdiv29115" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> BaseClass
{
    <span class="key">public</span> <span class="key">virtual</span> <span class="key">void</span> DisplayMessage()
    {
        Console.WriteLine(<span class="str">"Message from BaseClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> DerivedClass : BaseClass
{
    <span class="key">public</span> <span class="key">sealed</span> <span class="key">override</span> <span class="key">void</span> DisplayMessage()
    {
        Console.WriteLine(<span class="str">"Message from DerivedClass"</span>);
    }
}

<div style="background-color: #ffb6c154;"><span style="color:red;">// The following code will result in a compilation error because DisplayMessage is sealed</span>
<span class="key">public</span> <span class="key">class</span> FurtherDerivedClass : DerivedClass
{
    <span class="key">public</span> <span class="key">override</span> <span class="key">void</span> DisplayMessage()
    {
        Console.WriteLine(<span class="str">"Message from FurtherDerivedClass"</span>);
    }
}
</div>

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        DerivedClass derivedClass = <span class="key">new</span> DerivedClass();
        derivedClass.DisplayMessage();
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference between a Sealed class and a Sealed method</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th>Sealed Class</th>
            <th>Sealed Method</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A class that cannot be inherited</td>
            <td>A method that cannot be overridden in derived classes</td>
        </tr>
        <tr>
            <td>Prevents inheritance and ensures no class can derive from it</td>
            <td>Prevents further overriding of a method in derived classes</td>
        </tr>
        <tr>
            <td><pre class="pchl"><code><span class="key">public</span> <span class="key">sealed</span> <span class="key">class</span> MyClass { } </code></pre></td>
            <td><pre class="pchl"><code><span class="key">public</span> <span class="key">sealed</span> <span class="key">override</span> <span class="key">void</span> MyMethod() { } </code></pre></td>
        </tr>
        <tr>
            <td>Used when you want to restrict class inheritance</td>
            <td>Used in a derived class to prevent further method overriding</td>
        </tr>
        <tr>
            <td>Inheriting from a sealed class causes a compile-time error</td>
            <td>Overriding a sealed method in a derived class causes a compile-time error</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference between an Abstract method &amp; Virtual method</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th></th>
            <th>Abstract Method</th>
            <th>Virtual Method</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Declaration</th>
            <td>Declared with the abstract keyword in an abstract class</td>
            <td>Declared with the virtual keyword</td>
        </tr>
        <tr>
            <th>Implementation</th>
            <td>No implementation in the base class</td>
            <td>Can have an implementation in the base class</td>
        </tr>
        <tr>
            <th>Class Requirement</th>
            <td>Must be in an abstract class</td>
            <td>Can be in any class (abstract or concrete)</td>
        </tr>
        <tr>
            <th>Overriding</th>
            <td>Must be overridden in derived non-abstract classes</td>
            <td>Can be optionally overridden in derived classes</td>
        </tr>
        <tr>
            <th>Instantiation</th>
            <td>Cannot instantiate the class directly (must be abstract)</td>
            <td>Can instantiate the class directly</td>
        </tr>
        <tr>
            <th>Modifier Requirement</th>
            <td>Must be abstract (no other modifiers like static, sealed)</td>
            <td>Can be combined with other modifiers (sealed, override)</td>
        </tr>
        <tr>
            <th>Purpose</th>
            <td>To force derived classes to provide a specific implementation</td>
            <td>To provide a default implementation that derived classes can override</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the role of an Accessor and a Mutator in OOP?</strong></h3>



<p class="custp1 p-mb-0">Accessors and Mutators are methods used to access and modify the private fields of a class. These methods are often referred to as &#8220;getters&#8221; and &#8220;setters.&#8221;</p>



<p class="custp1 p-mb-0"><strong>Accessors (Getters) &#8211;</strong> used to read the value of a private field.</p>



<p class="custp1 p-mb-0"><strong>Mutators (Setters) &#8211;</strong> used to modify the value of a private field.</p>



<button class="shbtn" id="shbtn17252" onclick="showHideBlock(17252)">&#9660; <u>Show example</u></button>
<div id="shdiv17252" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Person
{
    <span class="key">private</span> <span class="key">string</span> name;

	<span class="com">// Property with Getter and Setter</span>
    <span class="key">public</span> <span class="key">string</span> Name
    {
        <span class="key">get</span> { <span class="key">return</span> name; }
        <span class="key">set</span> { name = value; }
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is reflection in OOP?</strong></h3>



<p class="custp1 p-mb-0">Reflection allows you to obtain information about assemblies, modules, types, and members (fields, properties, methods, etc.) at <strong>runtime</strong>. This includes examining <strong>metadata </strong>about types, accessing type information, and <strong>dynamically </strong>invoking methods or accessing properties.</p>



<button class="shbtn" id="shbtn69749" onclick="showHideBlock(69749)">&#9660; <u>Show example</u></button>
<div id="shdiv69749" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Getting Type Information</b></div>
<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">public</span> <span class="key">class</span> Person
{
    <span class="key">public</span> <span class="key">string</span> FirstName { get; set; }
    <span class="key">public</span> <span class="key">string</span> LastName { get; set; }

    <span class="key">public</span> <span class="key">void</span> PrintFullName()
    {
        Console.WriteLine($<span class="str">"{FirstName} {LastName}"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> Example
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
		<span class="com">// Getting the Type object using the typeof keyword</span>
        <span style="background:#f2f19d;"><span class="custkey">Type</span> personType = <span class="key">typeof</span>(Person);</span>

        <span class="com">// Display type information</span>
        Console.WriteLine(<span class="str">"Type Name: "</span> + personType.Name);
        Console.WriteLine(<span class="str">"Namespace: "</span> + personType.Namespace);

        <span class="com">// Display properties</span>
        Console.WriteLine(<span class="str">"Properties:"</span>);
        <span class="key">foreach</span> (<span class="key">var</span> prop <span class="key">in</span> personType.<span style="background:#f2f19d;">GetProperties()</span>)
        {
            Console.WriteLine(<span class="str">" - "</span> + prop.Name);
        }

        <span class="com">// Display methods</span>
        Console.WriteLine(<span class="str">"Methods:"</span>);
        <span class="key">foreach</span> (<span class="key">var</span> method <span class="key">in</span> personType.<span style="background:#f2f19d;">GetMethods()</span>)
        {
            Console.WriteLine(<span class="str">" - "</span> + method.Name);
        }
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Dynamic Method Invocation</b></div>
<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Reflection;

<span class="key">public</span> <span class="key">class</span> Person
{
    <span class="key">public</span> <span class="key">string</span> FirstName { get; set; }
    <span class="key">public</span> <span class="key">string</span> LastName { get; set; }

    <span class="key">public</span> <span class="key">void</span> PrintFullName()
    {
        Console.WriteLine($<span class="str">"{FirstName} {LastName}"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> Example
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Create an instance of Person using reflection</span>
        <span style="background:#f2f19d;"><span class="custkey">Type</span> personType = <span class="key">typeof</span>(Person);</span>
        <span class="key">object</span> personInstance = <span style="background:#f2f19d;">Activator.CreateInstance(personType);</span>

        <span class="com">// Set properties using reflection</span>
        <span class="custkey">PropertyInfo</span> firstNameProp = personType.GetProperty(<span class="str">"FirstName"</span>);
        <span class="custkey">PropertyInfo</span> lastNameProp = personType.GetProperty(<span class="str">"LastName"</span>);

        firstNameProp.SetValue(personInstance, <span class="str">"John"</span>);
        lastNameProp.SetValue(personInstance, <span class="str">"Doe"</span>);

        <span class="com">// Invoke method using reflection</span>
        <span class="custkey">MethodInfo</span> printMethod = personType.GetMethod(<span class="str">"PrintFullName"</span>);
        printMethod.Invoke(personInstance, <span class="key">null</span>);
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>Which of these terms defines the hiding of an object&#8217;s details from the other program?</strong></strong></h3>



<p class="custp1 p-mb-0"><strong>Select from the following answers:</strong> <br>a) Encapsulation<br>b) Abstraction<br>c) member hiding<br>d) None</p>



<p class="custp1 p-mb-0">Answer: <strong>(a) Encapsulation</strong></p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>what do you mean by &#8216;implicit&#8217; and &#8216;explicit&#8217;?</strong></h3>



<p class="custp1 p-mb-0"><strong>Implicit</strong> means something happens automatically without the programmer needing to specify it directly. In type conversion, an <strong>implicit conversion</strong> occurs when a value of one type is automatically converted to another type by the compiler, without needing an explicit cast by the programmer. </p>



<pre class="pchl"><code><span class="key">int</span> intNumber = 42;
<span class="com">// Implicit conversion from int to double</span>
<span class="key">double</span> doubleNumber = intNumber; </code></pre>
<br>



<p class="p-mb-0"><strong>Explicit</strong> means something is done deliberately and requires specific instructions from the programmer. In type conversion, an <strong>explicit conversion</strong> requires the programmer to use a cast or a specific method to convert a value from one type to another. This is often necessary when there is a potential for data loss or when converting between incompatible types.</p>



<pre class="pchl"><code><span class="key">double</span> doubleNumber = 42.5;
<span class="com">// Explicit conversion from double to int</span>
<span class="key">int</span> intNumber = (<span class="key">int</span>)doubleNumber; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Explain the &#8216;concept of reusability&#8217; in OOP.</strong></h3>



<p class="custp1 p-mb-0">Reusability in OOP refers to the ability to use existing code components in new applications or different parts of the same application. This is achieved through several key OOP concepts, including inheritance, polymorphism, and encapsulation, which help in writing modular, maintainable, and scalable code.</p>



<p class="custp1 p-mb-0"><strong><em>Benefits of Reusability:</em></strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Reduced Development Time</strong>: Reusing existing components reduces the time required to develop new features or applications.</li>



<li><strong>Increased Reliability</strong>: Reused code components are likely to be well-tested and proven in other applications, leading to more reliable software.</li>



<li><strong>Consistency</strong>: Using the same components across different parts of an application or different projects ensures consistent behavior and interface.</li>



<li><strong>Maintainability</strong>: Changes and bug fixes can be made in one place and automatically propagated to all instances where the component is used.</li>
</ol>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you test OOP code?</strong></h3>



<br>



<p class="p-mb-0"><strong><em>Approaches to Testing OOP Code: </em></strong></p>



<ul class="ol1 wp-block-list">
<li><strong>Unit Testing:</strong> Focuses on testing individual units (e.g., methods, classes) in isolation.</li>



<li><strong>Integration Testing:</strong> Tests the interactions between different classes and modules. Ensures that combined components work together as expected.</li>



<li><strong>System Testing:</strong> Tests the entire system as a whole. Ensures that the complete application functions as intended.</li>



<li><strong>Mocking:</strong> Replaces real objects with mock objects to isolate the unit of code being tested. Useful for testing classes that depend on external resources or other classes.</li>
</ul>



<p class="custp1 p-mb-0"><strong><em>Tools for Testing OOP Code:</em></strong></p>



<ul class="ol1 wp-block-list">
<li><strong>Unit Testing Frameworks</strong> like <span class="spanHT">NUnit</span>, <span class="spanHT">xUnit</span>.</li>



<li><strong>Mocking Frameworks</strong> like <span class="spanHT">Moq</span></li>
</ul>



<p class="custp1 p-mb-0"><strong><em>Steps to Test OOP Code:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Write Test Cases:</strong> Identify the methods and classes to be tested. Write test cases that cover different scenarios, including edge cases and error conditions.</li>



<li><strong>Use Assertions:</strong> Verify that the actual output matches the expected output using assertions. Common assertion methods include Assert.AreEqual, Assert.IsTrue, Assert.Throws, etc.</li>



<li><strong>Setup and Teardown:</strong> Initialize any necessary objects or state before each test (Setup). Clean up after each test to ensure tests are independent and repeatable (Teardown).</li>



<li><strong>Mock Dependencies:</strong> Use mocking frameworks to create mock objects for any dependencies. Inject mock objects into the class under test to isolate its behavior.</li>



<li><strong>Run Tests:</strong> Execute the tests using a test runner or IDE integration. Review the results and fix any failing tests.</li>
</ul>



<br><br><br>



<div id="download-questions" style="border: solid 1px lightblue; padding: 10px;">
<button class="shbtn" style="float: right; border-radius: 20px;" onclick="saveQuestionsAsPDF()">Download</button>
<div><span style="font-weight: bold; font-size: 20px; color: #7100e2;">Download all Questions as .PDF</span></div>
<div id="questions"><br><br><center><span style="color:#808080;"><i>loading&#8230;</i></span></center></div>
</div>



<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>



<style>
.shbtn {
    color: #fff;
    padding: 6px 12px;
    margin-top: 8px;
}
.shdt {
    box-shadow: lightblue 0px 1px 2px;
}
pre {
    margin-bottom: 0;
}
tbody>tr>th {
    font-weight: bold;
}
</style>

<script>
	function showHideBlock(val) {
		var btnx = document.getElementById("shbtn" + val);
		var divx = document.getElementById("shdiv" + val);

		if (divx.style.display === "none") {
			divx.style.display = "block";
			btnx.innerHTML = "&#9650; <u>Hide example</u>";
		} else {
			divx.style.display = "none";
			btnx.innerHTML = "&#9660; <u>Show example</u>";
		}
	}
</script>



<script>
window.onload = function (){
	var shbtnarr = document.getElementsByClassName("shbtn");
	var alreadySeen ={};
	console.log("shbtn count: " + shbtnarr.length);
	console.log("find duplicate - Start ---"); 
	for (element of shbtnarr) {
		if (alreadySeen[element.id]){
			console.log(element.id);
			alreadySeen[element.id] = false;
		}
		else {
			alreadySeen[element.id] = true;
		}
	}
	console.log("find duplicate - End ---"); 
	console.log()
	console.log("--- sh(alreadySeen) ids ---");
	console.log(alreadySeen);
	/* for (var key in alreadySeen)
	{
		console.log(key + " : " +  alreadySeen[key]);
	} */


	/*Sl.No for H3*/
	var h3arr = document.getElementsByClassName("hLBRed");
	var questions = document.getElementById("questions");
	questions.innerHTML = "<br><br><div><h2><center><b><u>OOPs Interview Questions</u></b></center></h2></div><br>";
	var count = 1;
	var searchResult = "";
	for (h3 of h3arr) {
		questions.innerHTML = questions.innerHTML + "<div>" + "<b>" + count + ")</b> " + h3.innerText.replace(/[^\w\s#?.,=<>]/gi, '').replace('<','&lt;').replace('>','&gt;') + "</div>";
		h3.innerHTML = "<b>" + count + ") " + h3.innerHTML + "</b>";
		h3.id = "q" + count;
		searchResult += '<div class="filter-list-item"><a href="#' + h3.id + '">' + h3.innerText + '</a></div>'
		count++;
	}

	document.getElementById('myList').innerHTML = searchResult;
};


/* Print Questions */
function saveQuestionsAsPDF(divId, title) { 
	if (document.getElementById("questions").innerText.trim().length == 0) return;

	var doc = new jsPDF();
	doc.fromHTML('<html><head></head><body><div>https://www.codeindotnet.com/all-interview-questions-and-answers/</div>' + document.getElementById("questions").innerHTML + '<br><br><br><div><b>See Other Questions &amp; Answers:</b> https://www.codeindotnet.com/all-interview-questions-and-answers/</div></body></html>');
	doc.save('oops-interview-questons.pdf');
}

</script>



<script type="text/javascript">
        document.getElementById("myInput").addEventListener("keyup",
    		function searchFilter() {
    			// Declare variables
    			var input, filter, div, divs, a, i;
    			input = document.getElementById('myInput').value.replace(/\s{2,}/g, ' ').trim().toUpperCase();
				arrFilters = input.split(' ');
    			div = document.getElementById('myList');
    			divs = div.getElementsByClassName('filter-list-item');
				
    			if (document.getElementById("myList").style.display == "none"){
    				document.getElementById("myList").style.display = "block";
    			}

				if(input.length == 0){
					for (i = 0; i < divs.length; i++) {
						divs[i].style.display = '';						
					}
				}
				else {
					// Loop through all list items, and hide those who don't match the search query
					for (i = 0; i < divs.length; i++) {
						a = divs[i].getElementsByTagName('a')[0];
						divs[i].style.display = 'none';
						for (j = 0; j < arrFilters.length; j++) {
							if ((arrFilters[j].length > 0) && (a.innerHTML.toUpperCase().indexOf(arrFilters[j]) > -1)) {
								divs[i].style.display = '';
								break;
							} 						
						}
						
					}
				}
    
		});
    </script>



<script>
function displayAllResult(){
	document.getElementById("myInput").value = ''
	div = document.getElementById('myList');
	divs = div.getElementsByClassName('filter-list-item');
	for (i = 0; i < divs.length; i++) {
		divs[i].style.display = '';						
	}
}
</script>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/oops-interview-questions-answers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>100+ C# Interview Questions &#038; Answers</title>
		<link>https://www.codeindotnet.com/csharp-interview-questions-answers/</link>
					<comments>https://www.codeindotnet.com/csharp-interview-questions-answers/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 14 Aug 2024 14:20:50 +0000</pubDate>
				<category><![CDATA[Interview Questions Answers]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=8095</guid>

					<description><![CDATA[C# (pronounced &#8220;C-sharp&#8221;) is a modern, object-oriented programming language developed by Microsoft. It is part of the .NET framework and is used to build a variety of applications, including web, desktop, mobile, and cloud-based applications. C# is known for its strong type-safety, garbage collection, and features that support software development. It is widely used in [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" src="/img/1/qa/csharp-interview-questions-answers-2.jpg" alt="csharp-C#-interview-questions-answers"/></figure></div>


<br>



<p>C# (pronounced &#8220;C-sharp&#8221;) is a modern, object-oriented programming language developed by Microsoft. It is part of the .NET framework and is used to build a variety of applications, including web, desktop, mobile, and cloud-based applications. C# is known for its strong type-safety, garbage collection, and features that support software development. It is widely used in enterprise environments and is one of the primary languages for developing applications on the Microsoft platform. Read more &#8211; <a href="/c-version-history-and-features/" target="_blank" rel="noopener">C# Version History and features</a>. Here, we will provide&nbsp;<strong><strong>100+ C# Interview Questions and Answers</strong></strong>&nbsp;which are suitable for both&nbsp;<strong><strong>freshers&nbsp;</strong></strong>and&nbsp;<strong><strong>experienced professionals</strong></strong>&nbsp;with 2, 5, and 10 years of experience.</p>



<br>



<h2 class="wp-block-heading has-text-align-center h2Cust1"><strong>C# Interview Questions &amp; Answers</strong></h2>



<p class="has-text-align-right"><strong><a href="#download-questions" data-type="internal" data-id="#download-questions">Download all Questions as .PDF</a></strong></p>



<div id="searchPopup">
	<div class="popup-header">			
		<span style="font-weight:bold;">Search: </span>
		<input type="text" id="myInput" autocomplete="off" placeholder=" type keyword(s) &amp; filter Questions..." onclick="document.getElementById('myList').style.display = 'block'; document.getElementById('btnpopclose').style.display = 'block';">
		<button onclick="displayAllResult();" style="padding: 5px 9px; border-radius: 10px; color:#fff;" >Clear</button>
		<button id="btnpopclose" class="popup-close" onclick="document.getElementById('myList').style.display = 'none'; document.getElementById('btnpopclose').style.display = 'none';">×</button>
	</div>
	<div id="myList"></div>		
</div>



<style>
.popup-close {
    font-size: 1.25rem;
    font-weight: 700;
    padding: .3125rem .625rem;
    border-radius: .3125rem;
    background-color: red;
    color: #fff;
    border: none;
    float: right;
    display: none;
    /*margin: -.3125rem;*/
}

#myInput{
width: calc(100% - 11.5625rem);
display:inline; 
border-radius: 10px; 
margin:0;
}

#searchPopup{
border: 1px solid #6a409759;
    padding: 10px;
    border-radius: 5px;
}

#myList{
line-height: 1.7; 
font-size: 16px; 
overflow-y: scroll; 
height: 250px; 
/*border-bottom: 3px lightgray solid;*/
display:none; 
margin-top: 15px;
}
</style>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you call a base class constructor from a derived class?</strong></h3>



<p class="custp1 p-mb-0">You can call a base class constructor from a derived class using the <span class="spanHT">base</span> keyword followed by the parameters required by the base class constructor. This is typically done in the derived class&#8217;s constructor.</p>



<button class="shbtn" id="shbtn3987" onclick="showHideBlock(3987)">&#9660; <u>Show example</u></button>
<div id="shdiv3987" style="display: none;">
<pre class="pchl"><code><span class="com">// Base class</span>
<span class="key">class</span> Person
{
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> <span class="key">int</span> Age { get; set; }

    <span class="com">// Base class constructor</span>
    <span class="key">public</span> Person(<span class="key">string</span> name, <span class="key">int</span> age)
    {
        Name = name;
        Age = age;
    }
}

<span class="com">// Derived class</span>
<span class="key">class</span> Employee : Person
{
    <span class="key">public</span> <span class="key">int</span> EmployeeId { get; set; }

    <span class="com">// Derived class constructor calling the base class constructor</span>
    <span class="key">public</span> Employee(<span class="key">string</span> name, <span class="key">int</span> age, <span class="key">int</span> employeeId) <span style="background:#f2f19d;">: <span class="key">base</span>(name, age)</span>
    {
        EmployeeId = employeeId;
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="com">// Creating an object of the derived class</span>
        Employee employee = <span class="key">new</span> Employee(<span class="str">"Alice"</span>, 30, 12345);

        <span class="com">// Displaying the initialized values</span>
        Console.WriteLine($<span class="str">"Name: {employee.Name}, Age: {employee.Age}, Employee ID: {employee.EmployeeId}"</span>);
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Usage of Destructor&nbsp;in C#</strong></h3>



<p class="custp1 p-mb-0">In C#, the garbage collector manages memory automatically, so destructors are not often needed for basic memory management tasks. Instead, the <span class="spanHT">IDisposable</span> interface and the <span class="spanHT">using</span> statement are preferred for deterministic disposal of resources. It should be used only when necessary because it can add overhead to the garbage collection process.</p>



<p class="custp1 p-mb-0"><strong><em>When to Use Destructors:</em></strong></p>



<ul class="ol1-mb-0 wp-block-list">
<li><strong>Unmanaged Resources</strong>: When your class uses unmanaged resources such as file handles, network connections, or database connections.</li>



<li><strong>Resource Management</strong>: When you need to ensure that resources are released when the object is no longer needed.</li>



<li><strong>Finalization Logic</strong>: When you need to perform specific finalization logic before an object is destroyed.</li>
</ul>



<button class="shbtn" id="shbtn99893" onclick="showHideBlock(99893)">&#9660; <u>Show example</u></button>
<div id="shdiv99893" style="display: none;">
<p class="custp1 p-mb-0"><b>Example with IDisposable</b></p>
<pre class="pchl"><code><span class="key">class</span> ResourceHolder <span style="background:#f2f19d;">: IDisposable</span>
{
    <span class="com">// Constructor</span>
    <span class="key">public</span> ResourceHolder()
    {
        <span class="com">// Acquire resources</span>
        Console.WriteLine(<span class="str">"Resource acquired."</span>);
    }

    <span class="com">// Dispose method for releasing resources</span>
    <span style="background:#f2f19d;"><span class="key">public</span> <span class="key">void</span> Dispose()</span>
    {
        <span class="com">// Release resources</span>
        Console.WriteLine(<span class="str">"Resource released."</span>);
    }

    <span class="key">public</span> <span class="key">void</span> DoWork()
    {
        Console.WriteLine(<span class="str">"Working..."</span>);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="key">using</span> (ResourceHolder rh = <span class="key">new</span> ResourceHolder())
        {
            rh.DoWork();
        } <span class="com">// ResourceHolder is disposed here</span>
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Static members in a class?</strong></h3>



<p class="custp1 p-mb-0">Static members in a class are members that belong to the class itself rather than to any specific instance of the class. This means that static members are shared among all instances of the class, and they can be accessed without creating an instance of the class.</p>



<p class="custp1 p-mb-0">Static members are typically stored in a separate area of memory reserved for the class, rather than in the heap where instance-specific data is stored. </p>



<p class="custp1 p-mb-0"><strong><em>Types of Static Members:</em></strong></p>



<ul class="ol1-mb-0 wp-block-list">
<li><strong>Static Fields</strong>: Variables that are shared among all instances of the class.</li>



<li><strong>Static Methods</strong>: Functions that can be called on the class itself, rather than on instances of the class.</li>



<li><strong>Static Properties</strong>: Properties that provide access to class-level data.</li>



<li><strong>Static Constructors</strong>: Special constructors used to initialize static fields or perform actions that need to be done only once.</li>
</ul>



<button class="shbtn" id="shbtn22114" onclick="showHideBlock(22114)">&#9660; <u>Show example</u></button>
<div id="shdiv22114" style="display: none;">
<pre class="pchl"><code><span class="key">class</span> MyClass
{
    <span class="com">// Static field</span>
    <span class="key">public</span> <span class="key">static</span> <span class="key">int</span> Counter = 0;

    <span class="com">// Static property</span>
    <span class="key">public</span> <span class="key">static</span> <span class="key">string</span> ClassName { get; } = <span class="str">"MyClass"</span>;

    <span class="com">// Instance field</span>
    <span class="key">public</span> <span class="key">int</span> InstanceNumber;

    <span class="com">// Static method</span>
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> IncrementCounter()
    {
        Counter++;
    }

    <span class="com">// Instance method</span>
    <span class="key">public</span> <span class="key">void</span> SetInstanceNumber(<span class="key">int</span> number)
    {
        InstanceNumber = number;
    }

    <span class="com">// Static constructor</span>
    <span class="key">static</span> MyClass()
    {
        Console.WriteLine(<span class="str">"Static constructor called."</span>);
    }

    <span class="com">// Instance constructor</span>
    <span class="key">public</span> MyClass()
    {
        Console.WriteLine(<span class="str">"Instance constructor called."</span>);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="com">// Accessing static members without creating an instance</span>
        Console.WriteLine($<span class="str">"Class name: {MyClass.ClassName}"</span>);
        MyClass.IncrementCounter();
        Console.WriteLine($<span class="str">"Counter: {MyClass.Counter}"</span>);

        <span class="com">// Creating instances and accessing instance members</span>
        MyClass obj1 = <span class="key">new</span> MyClass();
        obj1.SetInstanceNumber(1);
        Console.WriteLine($<span class="str">"Instance 1 number: {obj1.InstanceNumber}"</span>);

        MyClass obj2 = <span class="key">new</span> MyClass();
        obj2.SetInstanceNumber(2);
        Console.WriteLine($<span class="str">"Instance 2 number: {obj2.InstanceNumber}"</span>);

        <span class="com">// Static members remain the same across all instances</span>
        Console.WriteLine($<span class="str">"Counter: {MyClass.Counter}"</span>);
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Does C# support multiple inheritance? (or) Can a class implement multiple interfaces in C#?</strong></h3>



<p class="custp1 p-mb-0">No, C# does not support multiple inheritance for classes to avoid complexities like the diamond problem, where it becomes unclear which parent class&#8217;s method should be called when methods with the same name exist in multiple parent classes. This means a class in C# cannot directly inherit from more than one base class. However, C# does support multiple inheritance through interfaces, which allows a class to implement multiple interfaces.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is explicit Interface implementation?</strong></h3>



<p class="custp1 p-mb-0">Explicit interface implementation allows a class to implement interface members explicitly, providing a way to differentiate which interface&#8217;s method is being implemented when a class implements multiple interfaces that have members with the same signature. This helps avoid naming conflicts and ensures that interface methods are only accessible through an interface reference.</p>



<button class="shbtn" id="shbtn11572" onclick="showHideBlock(11572)">&#9660; <u>Show example</u></button>
<div id="shdiv11572" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">interface</span> IFirstInterface
{
    <span class="key">void</span> Display();
}

<span class="key">public</span> <span class="key">interface</span> ISecondInterface
{
    <span class="key">void</span> Display();
}

<span class="key">public</span> <span class="key">class</span> MyClass : IFirstInterface, ISecondInterface
{
    <span class="com">// Explicit implementation of IFirstInterface.Display</span>
    <span class="key">void</span> IFirstInterface.Display()
    {
        Console.WriteLine(<span class="str">"Display method from IFirstInterface"</span>);
    }

    <span class="com">// Explicit implementation of ISecondInterface.Display</span>
    <span class="key">void</span> ISecondInterface.Display()
    {
        Console.WriteLine(<span class="str">"Display method from ISecondInterface"</span>);
    }

    <span class="com">// Regular class method</span>
    <span class="key">public</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(<span class="str">"Display method from MyClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        MyClass obj = <span class="key">new</span> MyClass();
        obj.Display(); <span class="com">// Calls the regular class method</span>

        <span class="com">// Calls the explicit interface implementation of IFirstInterface.Display</span>
        <span style="background:#f2f19d;">IFirstInterface first = obj;</span>
        <span style="background:#f2f19d;">first.Display();</span> <span class="com">// Output: Display method from IFirstInterface</span>

        <span class="com">// Calls the explicit interface implementation of ISecondInterface.Display</span>
        <span style="background:#f2f19d;">ISecondInterface second = obj;</span>
        <span style="background:#f2f19d;">second.Display();</span> <span class="com">// Output: Display method from ISecondInterface</span>
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the work of a constructor?</strong></h3>



<p class="custp1 p-mb-0">A constructor creates and initializes the objects in an application.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can we declare a constructor to private?</strong></h3>



<p class="custp1 p-mb-0">Yes</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a constructor initializer in C#?</strong></h3>



<p class="custp1 p-mb-0">A constructor initializer in C# is a way to specify that a constructor should call another constructor in the same class (using <span class="spanHT">this</span>) or a constructor in the base class (using <span class="spanHT">base</span>) before executing the rest of the constructor&#8217;s body. This is useful for reusing constructor logic and ensuring that base class constructors are properly called. </p>



<p class="custp1 p-mb-0"><strong><em>Types of Constructor Initializers:</em></strong></p>



<ol class="ol1 ol1-mb-0">
<li class="custp1"><strong>&#8216;this&#8217; Initializer</strong> is used to call another constructor in the same class. It helps to avoid code duplication by reusing constructor logic.</li>
<button class="shbtn" id="shbtn22769" onclick="showHideBlock(22769)">&#9660; <u>Show example</u></button>
<div id="shdiv22769" style="display: none;" class="shdt" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Example 1:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Example {
    <span class="key">public</span> <span class="key">int</span> x;
    <span class="key">public</span> Example() <span style="background:#f2f19d;">: <span class="key">this</span>(10) {}</span>
    <span class="key">public</span> Example(<span class="key">int</span> x) {
        this.x = x;
    }
} </code></pre>


<br>
<div style="padding-left: 0.3125rem;"><b>Example 2:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Person
{
    <span class="key">public</span> <span class="key">string</span> FirstName { get; set; }
    <span class="key">public</span> <span class="key">string</span> LastName { get; set; }

    <span class="com">// Constructor with two parameters</span>
    <span class="key">public</span> Person(<span class="key">string</span> firstName, <span class="key">string</span> lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    <span class="com">// Constructor with one parameter, calls the two-parameter constructor</span>
    <span class="key">public</span> Person(<span class="key">string</span> fullName) <span style="background:#f2f19d;">: <span class="key">this</span>(fullName.Split(' ')[0], fullName.Split(' ')[1])</span>
    {
    }
} </code></pre>


</div>

<li class="custp1"><strong>&#8216;base&#8217; Initializer</strong> is used to call a constructor in the base class. Ensures that the base class is properly initialized.</li>
<button class="shbtn" id="shbtn68784" onclick="showHideBlock(68784)">&#9660; <u>Show example</u></button>
<div id="shdiv68784" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Employee : Person
{
    <span class="key">public</span> <span class="key">int</span> EmployeeId { get; set; }

    <span class="com">// Constructor for Employee, calls the base class constructor</span>
    <span class="key">public</span> Employee(<span class="key">string</span> firstName, <span class="key">string</span> lastName, <span class="key">int</span> employeeId) <span style="background:#f2f19d;">: <span class="key">base</span>(firstName, lastName)</span>
    {
        EmployeeId = employeeId;
    }

    <span class="com">// Constructor for Employee with full name, calls the base class constructor with full name</span>
    <span class="key">public</span> Employee(<span class="key">string</span> fullName, <span class="key">int</span> employeeId) <span style="background:#f2f19d;">: <span class="key">base</span>(fullName)</span>
    {
        EmployeeId = employeeId;
    }
} </code></pre>


</div>


</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How to prevent a public class method to be overridden in drive class?</strong></h3>



<p class="custp1 p-mb-0">Make method sealed by using <span class="spanHT">sealed</span> keyword.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How to stop a class being inherited by another class?</strong></h3>



<p class="custp1 p-mb-0">Make the class sealed by using <span class="spanHT">sealed</span> keyword.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How to prevent a class being instantiated?</strong></h3>



<p class="custp1 p-mb-0">Make class <span class="spanHT">abstract</span> or <span class="spanHT">static</span></p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can you derive a static method of base class in child class?</strong></h3>



<p class="custp1 p-mb-0">No, you cannot derive a static method of a base class in a child class. In C#, static methods belong to the class itself rather than to any instance of the class. This means they are not inherited by derived classes in the same way that instance methods are.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can you override a normal public method of base class and make it static?</strong></h3>



<p class="custp1 p-mb-0">No , the method signature should be same to be overridden.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How to override a private virtual method?</strong></h3>



<p class="custp1 p-mb-0">You cannot override a private method.</p>



<br><br><br>



<h3 class="wp-block-heading"><strong>What is the difference between &#8216;override&#8217; and &#8216;new&#8217; keywords in C#?</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th>override</th>
            <th>new</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Extends or modifies a virtual/abstract method in a base class</td>
            <td>Hides a method, property, indexer, or event inherited from a base class</td>
        </tr>
        <tr>
            <td>Requires the base method to be marked as virtual, abstract, or override</td>
            <td>Can hide any base class member, whether virtual or not</td>
        </tr>
        <tr>
            <td>Supports runtime polymorphism</td>
            <td>Does not support runtime polymorphism</td>
        </tr>
        <tr>
            <td>Method Call Determined by the object&#39;s runtime type</td>
            <td>Determined by the reference type</td>
        </tr>
        <tr>
            <td>Base Class Method must exist in the base class as virtual, abstract, or override</td>
            <td>Can exist with any modifier in the base class</td>
        </tr>
        <tr>
            <td>Keyword must be virtual, abstract, or override in the base class</td>
            <td>Can be any keyword in the base class</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Early and Late Binding?</strong></h3>



<p class="custp1 p-mb-0"><strong>Early Binding:</strong> Methods or properties are determined at compile time, resulting in faster execution and early error detection.</p>



<p class="custp1 p-mb-0"><strong>Late Binding</strong>: Methods or properties are determined at run time, offering more flexibility but potentially slower execution and late error detection.</p>



<button class="shbtn" id="shbtn90352" onclick="showHideBlock(90352)">&#9660; <u>Show example</u></button>
<div id="shdiv90352" style="display: none;">
<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Reflection;

<span class="key">public</span> <span class="key">class</span> BindingExample
{
    <span class="key">public</span> <span class="key">void</span> ShowMessage()
    {
        Console.WriteLine(<span class="str">"Binding Example"</span>);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        BindingExample example = <span class="key">new</span> BindingExample();
        example.ShowMessage(); <span class="com">// Early binding</span>
		
		Type type = Type.GetType(<span class="str">"BindingExample"</span>);
        <span class="key">object</span> obj = Activator.CreateInstance(type);
        MethodInfo method = type.GetMethod(<span class="str">"ShowMessage"</span>);
        method.Invoke(obj, <span class="key">null</span>); <span class="com">// Late binding</span>
    }
} </code></pre>

</div>



<br><br><br>
<table>
    <thead>
        <tr>
            <th></th>
            <th>Early Binding</th>
            <th>Late Binding</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Determination Time</th>
            <td>Compile Time</td>
            <td>Run Time</td>
        </tr>
        <tr>
            <th>Performance</th>
            <td>Faster</td>
            <td>Slower</td>
        </tr>
        <tr>
            <th>Type Safety</th>
            <td>Checked at compile time</td>
            <td>Checked at run time</td>
        </tr>
        <tr>
            <th>Flexibility</th>
            <td>Less flexible</td>
            <td>More flexible</td>
        </tr>
        <tr>
            <th>Error Detection</th>
            <td>Compile time (early detection)</td>
            <td>Run time (late detection)</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can namespace contain the private class?</strong></h3>



<p class="custp1 p-mb-0">No, having a single private class does not mean anything , it is applicable only in case of nested class.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can we have Sealed Method in abstarct class ?</strong></h3>



<p class="custp1 p-mb-0">No, an abstract class cannot have a sealed method directly because abstract methods must be overridden in derived classes, and sealing is meant to prevent further overriding.</p>



<p class="custp1 p-mb-0"><strong><em>How to Work Around:</em></strong> ou can achieve a similar effect by providing a virtual method in the abstract class, then override and seal it in a derived class.</p>



<button class="shbtn" id="shbtn60815" onclick="showHideBlock(60815)">&#9660; <u>Show example</u></button>
<div id="shdiv60815" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">abstract</span> <span class="key">class</span> BaseClass
{
    <span class="com">// Virtual method in the abstract class</span>
    <span class="key">public</span> <span class="key">virtual</span> <span class="key">void</span> DisplayMessage()
    {
        Console.WriteLine(<span class="str">"Message from BaseClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> DerivedClass : BaseClass
{
    <span class="com">// Overriding and sealing the method in the derived class</span>
    <span class="key">public</span> <span class="key">sealed</span> <span class="key">override</span> <span class="key">void</span> DisplayMessage()
    {
        Console.WriteLine(<span class="str">"Message from DerivedClass"</span>);
    }
}

<span class="com">// The following class would cause a compilation error because DisplayMessage is sealed</span>
<span class="com">// public class FurtherDerivedClass : DerivedClass</span>
<span class="com">// {</span>
<span class="com">//     public override void DisplayMessage()</span>
<span class="com">//     {</span>
<span class="com">//         Console.WriteLine("Message from FurtherDerivedClass");</span>
<span class="com">//     }</span>
<span class="com">// }</span>

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        DerivedClass derivedClass = <span class="key">new</span> DerivedClass();
        derivedClass.DisplayMessage(); <span class="com">// Output: Message from DerivedClass</span>
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Why cannot I have abstract static methods in C#?</strong></h3>



<p class="custp1">You cannot have abstract static methods because the concepts of &#8220;abstract&#8221; and &#8220;static&#8221; are fundamentally incompatible. <br><strong>Abstract Methods</strong>: Require overriding in derived classes. <br><strong>Static Methods</strong>: Cannot be overridden and belong to the class itself.</p>



<p class="p-mb-0"><strong>Implementation Requirement</strong>: Abstract methods are intended to be overridden and given concrete implementations in derived classes. However, static methods cannot be overridden. </p>



<p class="custp1 p-mb-0"><strong>Instance Context</strong>: Abstract methods operate within the context of an instance of a class, whereas static methods operate without any instance context. </p>



<p class="custp1 p-mb-0">The need for overriding (abstract) and the inability to be overridden (static) make it logically impossible to have a method that is both abstract and static.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can we have Multiple Main Methods in one .cs file?</strong></h3>



<p class="custp1 p-mb-0">Yes</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can you declare the override method static while the original method is non-static?</strong></h3>



<p class="custp1 p-mb-0">No, you can&#8217;t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can you override private virtual methods?</strong></h3>



<p class="custp1 p-mb-0">No, you cannot access private methods in inherited classes.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Static methods cannot use Non-Static members. True or False?</strong></h3>



<p class="custp1 p-mb-0">True</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>If the Function has same parameter but different return type (int and float), Is it a overloading?</strong></h3>



<p class="custp1 p-mb-0">No, having a function with the same parameter list but different return types is not considered overloading in C#. Function overloading requires the parameter lists to differ in number, type, or order of parameters, not just the return type.</p>



<button class="shbtn" id="shbtn10313" onclick="showHideBlock(10313)">&#9660; <u>Show example</u></button>
<div id="shdiv10313" style="display: none;">
<br>
<div><b>InCorrect Overloading: </b> The following code will cause a compilation error in C# because overloading by return type alone is not allowed.</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Example
{
    <span class="com">// This method returns an integer</span>
    <span class="key">public</span> <span class="key">int</span> Calculate(<span class="key">int</span> number)
    {
        <span class="key">return</span> number * 2;
    }

    <span class="com">// This method returns a float</span>
    <span class="key">public</span> <span class="key">float</span> Calculate(<span class="key">int</span> number)
    {
        <span class="key">return</span> number * 2.0f;
    }
} </code></pre>

<br><br>

<div><b>Correct Overloading: </b>You need to change the parameter list to achieve overloading. For example:</div>

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Example
{
    <span class="com">// This method returns an integer and takes an int parameter</span>
    <span class="key">public</span> <span class="key">int</span> Calculate(<span style="background:#f2f19d;"><span class="key">int</span> number</span>)
    {
        <span class="key">return</span> number * 2;
    }

    <span class="com">// This method returns a float and takes a float parameter</span>
    <span class="key">public</span> <span class="key">float</span> Calculate(<span style="background:#f2f19d;"><span class="key">float</span> number</span>)
    {
        <span class="key">return</span> number * 2.0f;
    }

    <span class="com">// This method returns a double and takes two int parameters</span>
    <span class="key">public</span> <span class="key">double</span> Calculate(<span style="background:#f2f19d;"><span class="key">int</span> number1, <span class="key">int</span> number2</span>)
    {
        <span class="key">return</span> number1 * number2;
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Overloading is Static Polymorphism and Overriding is Dynamic Polymorphism? True or False?</strong></h3>



<p class="custp1 p-mb-0">True</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the default access modifiers for various elements in C#?</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th>Element Type</th>
            <th>Default Access Modifier</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Top-Level Class</td>
            <td>internal</td>
        </tr>
        <tr>
            <td>Nested Class</td>
            <td>private</td>
        </tr>
        <tr>
            <td>Struct</td>
            <td>internal</td>
        </tr>
        <tr>
            <td>Interface</td>
            <td>internal</td>
        </tr>
        <tr>
            <td>Enum</td>
            <td>public</td>
        </tr>
        <tr>
            <td>Delegate</td>
            <td>internal</td>
        </tr>
        <tr>
            <td>Class Member (Field, Method, Property, Event)</td>
            <td>private</td>
        </tr>
        <tr>
            <td>Struct Member (Field, Method, Property, Event)</td>
            <td>private</td>
        </tr>
        <tr>
            <td>Enum Member</td>
            <td>public</td>
        </tr>
        <tr>
            <td>Interface Member (Method, Property, Event)</td>
            <td>public</td>
        </tr>
        <tr>
            <td>Constructor</td>
            <td>private</td>
        </tr>
        <tr>
            <td>Destructor</td>
            <td>private</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>Why is a const variable available within a static method?</strong></strong></h3>



<br>



<p class="p-mb-0"><span class="spanHT">const</span> members are implicitly static. They belong to the class rather than a specific instance. Because they are static, <span class="spanHT">const</span> variables are accessible within static methods without needing an instance of the class.</p>



<p class="custp1 p-mb-0">A static method can only access other static members (fields, properties, methods) of the class. Since <span class="spanHT">const</span> variables are static, they can be accessed from within static methods.</p>



<button class="shbtn" id="shbtn19091" onclick="showHideBlock(19091)">&#9660; <u>Show example</u></button>
<div id="shdiv19091" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Example
{
    <span class="com">// Const variable (implicitly static)</span>
    <span class="key">public</span> <span class="key">const</span> <span class="key">int</span> ConstValue = 10;

    <span class="com">// Static method</span>
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> StaticMethod()
    {
        <span class="com">// Accessing the const variable</span>
        Console.WriteLine(ConstValue);
    }

    <span class="com">// Instance method</span>
    <span class="key">public</span> <span class="key">void</span> InstanceMethod()
    {
        <span class="com">// Accessing the const variable</span>
        Console.WriteLine(ConstValue);
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Calling the static method</span>
        Example.StaticMethod();

        <span class="com">// Creating an instance and calling the instance method</span>
        Example example = <span class="key">new</span> Example();
        example.InstanceMethod();
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How does C# handle Method Hiding?</strong></h3>



<p class="custp1 p-mb-0">Method hiding is done using the <span class="spanHT">new</span> keyword. Method hiding occurs when a derived class defines a method with the same name as a method in its base class. The new method hides the base class method. (continue reading the next Question to see a sample example for Hiding Members).</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Use of &#8220;New&#8221; keyword in C#</strong></h3>



<br>



<p class="p-mb-0">The <span class="spanHT">new</span> keyword in C# has multiple uses.</p>



<p class="custp1 p-mb-0"><strong>1. Creating Objects:</strong> The <span class="spanHT">new</span> keyword is used to create instances of types (objects). This is the most common use.</p>



<pre class="pchl"><code><span class="com">// Creating an instance of MyClass</span>
MyClass obj = <span class="key">new</span> MyClass(); </code></pre>
<br>



<p class="p-mb-0"><strong>2) Hiding Members:</strong> The <span class="spanHT">new</span> keyword can be used to hide a member inherited from a base class. This is known as member hiding.</p>



<button class="shbtn" id="shbtn60878" onclick="showHideBlock(60878)">&#9660; <u>Show example</u></button>
<div id="shdiv60878" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> BaseClass
{
    <span class="key">public</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(<span class="str">"Display from BaseClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> DerivedClass : BaseClass
{
    <span class="com">// Hides the Display method in the base class</span>
    <span class="key">public</span> <span style="background:#f2f19d;"><span class="key">new</span> <span class="key">void</span> Display()</span>
    {
        Console.WriteLine(<span class="str">"Display from DerivedClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        DerivedClass obj = <span class="key">new</span> DerivedClass();
        obj.Display(); <span class="com">// Output: Display from DerivedClass</span>

        BaseClass baseObj = obj;
        baseObj.Display(); <span class="com">// Output: Display from BaseClass</span>
    }
} </code></pre>

</div>
<br><br>



<p class="p-mb-0"><strong>3) Creating Instances of Anonymous Types:</strong> The <span class="spanHT">new</span> keyword is also used to create instances of anonymous types.</p>



<pre class="pchl"><code><span class="key">var</span> anonType = <span class="key">new</span> { Name = <span class="str">"John"</span>, Age = 30 }; </code></pre>
<br>



<p class="p-mb-0"><strong>4) Creating Instances of Array:</strong> The <span class="spanHT">new</span> keyword is used to create instances of arrays.</p>



<pre class="pchl"><code>int[] numbers = <span class="key">new</span> int[5]; </code></pre>
<br>



<p class="p-mb-0"><strong>5) Creating Instances of Value Types:</strong> The <span class="spanHT">new</span> keyword can be used to create instances of value types.</p>



<button class="shbtn" id="shbtn72579" onclick="showHideBlock(72579)">&#9660; <u>Show example</u></button>
<div id="shdiv72579" style="display: none;">
<pre class="pchl"><code><span class="key">public</span> <span class="key">struct</span> MyStruct
{
    <span class="key">public</span> <span class="key">int</span> X;
    <span class="key">public</span> <span class="key">int</span> Y;
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        MyStruct point = <span class="key" style="background:#f2f19d;">new</span> MyStruct();
        point.X = 5;
        point.Y = 10;
        Console.WriteLine($<span class="str">"X: {point.X}, Y: {point.Y}"</span>);
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Boxing and Unboxing in C#</strong></h3>



<br>



<p class="p-mb-0"><strong>Boxing:</strong> Converting a value type to a reference type</p>



<pre class="pchl"><code><span class="key">object</span> obj = 123; </code></pre>
<br>



<p class="p-mb-0"><strong>Unboxing:</strong> Converting a reference type back to a value type</p>



<pre class="pchl"><code><span class="key">int</span> num = (<span class="key">int</span>)obj; </code></pre>
<br>



<p class="p-mb-0">Boxing and unboxing involve additional overhead due to heap allocation and type conversion, which can affect performance. Useful when you need to treat value types as objects, such as when storing them in non-generic collections.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What do you mean by &#8216;Mutable&#8217; in C#</strong></h3>



<p class="custp1 p-mb-0">In C#, an object is considered <strong>mutable</strong> if its state or fields can be changed after it is created. Mutable objects allow modification of their data members.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference between String Vs StringBuilder</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th></th>
            <th>String</th>
            <th>StringBuilder</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Immutability</th>
            <td>Immutable (cannot be changed after creation)</td>
            <td>Mutable (can be changed after creation)</td>
        </tr>
        <tr>
            <th>Performance for Modifications</th>
            <td>Inefficient for frequent modifications (creates new instances)</td>
            <td>Efficient for frequent modifications (modifies in place)</td>
        </tr>
        <tr>
            <th>Memory Usage</th>
            <td>Higher memory usage due to creation of new instances</td>
            <td>Lower memory usage due to in-place modifications</td>
        </tr>
        <tr>
            <th>Use Case</th>
            <td>Suitable for operations with few or no modifications</td>
            <td>Suitable for operations with many modifications</td>
        </tr>
        <tr>
            <th>Methods for Modification</th>
            <td>Methods like Replace, Concat, Substring</td>
            <td>Methods like Append, Insert, Remove, Replace</td>
        </tr>
        <tr>
            <th>Namespace</th>
            <td>System</td>
            <td>System.Text</td>
        </tr>
        <tr>
            <th>Thread Safety</th>
            <td>Thread-safe (due to immutability)</td>
            <td>Not thread-safe without external synchronization</td>
        </tr>
    </tbody>
</table>



<button class="shbtn" id="shbtn86989" onclick="showHideBlock(86989)">&#9660; <u>Show example</u></button>
<div id="shdiv86989" style="display: none;" class="shdt">
<br>
<div style="padding-left: 0.3125rem;"><b>String:</b></div>
<pre class="pchl"><code><span class="key">string</span> str = <span class="str">"Hello"</span>;
str += <span class="str">" World"</span>;  <span class="com">// Creates a new string instance</span>
Console.WriteLine(str); // Output: Hello World / Output: Hello World </code></pre>

<br><br>

<div style="padding-left: 0.3125rem;"><b>StringBuilder:</b></div>
<pre class="pchl"><code><span class="custkey">StringBuilder</span> sb = <span class="key">new</span> <span class="custkey">StringBuilder</span>(<span class="str">"Hello"</span>);
sb.Append(<span class="str">" World"</span>);  <span class="com">// Modifies the existing instance</span>
Console.WriteLine(sb.ToString()); // Output: Hello World / Output: Hello World </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference between &#8216;Const&#8217; Vs &#8216;Read Only&#8217;</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th>const</th>
            <th>readonly</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Must be assigned at declaration</td>
            <td>Can be assigned at declaration or in a constructor</td>
        </tr>
        <tr>
            <td>Immutable &#8211; Once assigned, cannot be changed.</td>
            <td>Immutable after initialization -Can be assigned once (at declaration or in a constructor) and then cannot be changed.</td>
        </tr>
        <tr>
            <td>Compile-time constant</td>
            <td>Run-time constant</td>
        </tr>
        <tr>
            <td>Static by default</td>
            <td>Can be instance-level or static</td>
        </tr>
        <tr>
            <td>Limited to strings and primitive types</td>
            <td>Can be used with any type, including reference types</td>
        </tr>
        <tr>
            <td>Initialized Only in the field declaration</td>
            <td>Initialized in the field declaration or in a constructor</td>
        </tr>
        <tr>
            <td>Better performance due to inlining</td>
            <td>Slight overhead due to run-time evaluation</td>
        </tr>
        <tr>
            <td>Requires the const keyword</td>
            <td>Requires the readonly keyword</td>
        </tr>
        <tr>
            <td>Allocated once per program</td>
            <td>Allocated once per instance (if not static)</td>
        </tr>
    </tbody>
</table>



<button class="shbtn" id="shbtn90718" onclick="showHideBlock(90718)">&#9660; <u>Show example</u></button>
<div id="shdiv90718" style="display: none;" class="shdt">
<br>
<div style="padding-left: 0.3125rem;"><b>const:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Example
{
    <span style="background:#f2f19d;"><span class="key">public</span> <span class="key"><b>const</b></span> <span class="key">int</span> MaxValue = 100;</span>

    <span class="key">public</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(MaxValue);
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>readonly:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Example
{
    <span style="background:#f2f19d;"><span class="key">public</span> <span class="key"><b>readonly</b></span> <span class="key">int</span> MaxValue;</span>

    <span class="key">public</span> Example(<span class="key">int</span> maxValue)
    {
        <span style="background:#f2f19d;">MaxValue = maxValue;</span>
    }

    <span class="key">public</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(MaxValue);
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Virtual method?</strong></h3>



<p class="custp1 p-mb-0">A <strong>virtual method</strong> is a method in a base class that can be overridden by a derived class. This allows the derived class to provide a specific implementation of the method, which will be used instead of the base class implementation. The <span class="spanHT">virtual</span> keyword is used in the base class, and the <span class="spanHT">override</span> keyword is used in the derived class.</p>



<button class="shbtn" id="shbtn9797" onclick="showHideBlock(9797)">&#9660; <u>Show example</u></button>
<div id="shdiv9797" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Base Class</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> BaseClass
{
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">virtual</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(<span class="str">"Display method in BaseClass."</span>);
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Derived Class</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> DerivedClass : BaseClass
{
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">override</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(<span class="str">"Display method in DerivedClass."</span>);
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Collection in C#?</strong></h3>



<p class="custp1">A <strong>Collection</strong> refers to a data structure that is used to store, manage, and manipulate groups of related objects. Collections provide various ways to store, access, and iterate over data, making them fundamental in programming for handling multiple items. </p>



<p class="p-mb-0"><strong><em>Types of Collections:</em></strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Non-Generic Collections</strong>: These are collections that can store any type of object. They are part of the <em>System.Collections</em> namespace. <br>Example: <span class="spanHT">ArrayList</span>, <span class="spanHT">Hashtable</span>, <span class="spanHT">Queue</span>, <span class="spanHT">Stack</span>, <span class="spanHT">SortedList</span>.</li>



<li class="custp1"><strong>Generic Collections</strong>: These collections provide type safety by allowing you to specify the type of elements stored in the collection. They are part of the <em>System.Collections.Generic</em> namespace.<br>Example: <span class="spanHT">List</span>, <span class="spanHT">Dictionary</span>, <span class="spanHT">Queue</span>, <span class="spanHT">Stack</span>, <span class="spanHT">SortedList</span>, <span class="spanHT">HashSet</span>, <span class="spanHT">LinkedList</span></li>



<li class="custp1"><strong>Concurrent Collections</strong>: These collections are designed for multi-threaded scenarios, providing thread-safe operations. They are part of the <em>System.Collections.Concurrent</em> namespace.<br>Example: <span class="spanHT">ConcurrentDictionary</span>, <span class="spanHT">ConcurrentQueue</span>, <span class="spanHT">ConcurrentStack</span>, <span class="spanHT">ConcurrentBag</span></li>
</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement a custom collection class?</strong></h3>



<p class="custp1 p-mb-0">Implementing a custom collection class in C# involves creating a class that encapsulates a collection of items and provides methods for adding, removing, and manipulating these items. To integrate well with .NET, it&#8217;s often useful to implement standard collection interfaces like <span class="spanHT">IEnumerable&lt;T&gt;</span>, <span class="spanHT">ICollection&lt;T&gt;</span>, or <span class="spanHT">IList&lt;T&gt;</span>.</p>



<button class="shbtn" id="shbtn24459" onclick="showHideBlock(24459)">&#9660; <u>Show example</u></button>
<div id="shdiv24459" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Below is an example of how to implement a simple Custom Collection class that implements the &#39;ICollection<T>&#39; interface.</b>
<br><Br>
<b>CustomCollection.cs</b>
</div>

<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Collections;
<span class="key">using</span> System.Collections.Generic;

<span class="key">public</span> <span class="key">class</span> CustomCollection&lt;T&gt <span style="background:#f2f19d;">: ICollection&lt;T&gt</span>
{
    <span class="key">private</span> List&lt;T&gt _items = <span class="key">new</span> List&lt;T&gt();

    <span class="com">// Add an item to the collection</span>
    <span class="key">public</span> <span class="key">void</span> Add(T item)
    {
        _items.Add(item);
    }

    <span class="com">// Clear all items from the collection</span>
    <span class="key">public</span> <span class="key">void</span> Clear()
    {
        _items.Clear();
    }

    <span class="com">// Check if the collection contains a specific item</span>
    <span class="key">public</span> <span class="key">bool</span> Contains(T item)
    {
        <span class="key">return</span> _items.Contains(item);
    }

    <span class="com">// Copy the collection to an array starting at a specific index</span>
    <span class="key">public</span> <span class="key">void</span> CopyTo(T[] array, <span class="key">int</span> arrayIndex)
    {
        _items.CopyTo(array, arrayIndex);
    }

    <span class="com">// Remove an item from the collection</span>
    <span class="key">public</span> <span class="key">bool</span> Remove(T item)
    {
        <span class="key">return</span> _items.Remove(item);
    }

    <span class="com">// Get the number of items in the collection</span>
    <span class="key">public</span> <span class="key">int</span> Count
    {
        <span class="key">get</span> { <span class="key">return</span> _items.Count; }
    }

    <span class="com">// Get a value indicating whether the collection is read-only</span>
    <span class="key">public</span> <span class="key">bool</span> IsReadOnly
    {
        <span class="key">get</span> { <span class="key">return</span> false; }
    }

    <span class="com">// Get an enumerator that iterates through the collection</span>
    <span class="key">public</span> IEnumerator&lt;T&gt GetEnumerator()
    {
        <span class="key">return</span> _items.GetEnumerator();
    }

    <span class="com">// Get an enumerator that iterates through the collection (non-generic version)</span>
    IEnumerator IEnumerable.GetEnumerator()
    {
        <span class="key">return</span> _items.GetEnumerator();
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Using the Custom Collection</b>
<br><br>
<b>Program.cs</b>
</div>

<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Create an instance of the custom collection</span>
        <span style="background:#f2f19d;">CustomCollection&lt;<span class="key">string</span>&gt collection = <span class="key">new</span> CustomCollection&lt;<span class="key">string</span>&gt();</span>

        <span class="com">// Add items to the collection</span>
        collection.Add(<span class="str">"Apple"</span>);
        collection.Add(<span class="str">"Banana"</span>);
        collection.Add(<span class="str">"Cherry"</span>);

        <span class="com">// Check if the collection contains an item</span>
        Console.WriteLine($<span class="str">"Contains 'Banana': {collection.Contains("</span>Banana<span class="str">")}"</span>);

        <span class="com">// Remove an item from the collection</span>
        collection.Remove(<span class="str">"Banana"</span>);

        <span class="com">// Iterate through the collection</span>
        <span class="key">foreach</span> (<span class="key">var</span> item <span class="key">in</span> collection)
        {
            Console.WriteLine(item);
        }

        <span class="com">// Clear the collection</span>
        collection.Clear();
        Console.WriteLine($<span class="str">"Count after clearing: {collection.Count}"</span>);
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is ArrayList? When to use?</strong></h3>



<p class="custp1 p-mb-0">An <strong>ArrayList</strong> is a non-generic collection in C# that can store elements of any type, including both value types and reference types. It is part of the <span class="spanHT">System.Collections</span> namespace. Unlike arrays, the size of an ArrayList can dynamically increase or decrease as elements are added or removed. </p>



<p class="custp1 p-mb-0"><strong><em>When to Use:</em></strong></p>



<ul class="ol1 wp-block-list">
<li><strong>When Type Safety is Not a Concern</strong>: Use ArrayList when you do not need type safety and are working with a collection of objects of different types.</li>



<li><strong>Legacy Code</strong>: ArrayList is useful when maintaining or working with legacy code that already uses this collection.</li>



<li><strong>Quick Prototyping</strong>: For quick prototyping or small scripts where performance and type safety are not critical, ArrayList can be convenient.</li>
</ul>



<p class="custp1 p-mb-0"><strong><em>Considerations:</em></strong></p>



<ul class="ol1 wp-block-list">
<li><strong>Type Safety</strong>: ArrayList does not provide compile-time type checking. This can lead to runtime errors if incorrect types are added or accessed.</li>



<li><strong>Performance</strong>: ArrayList can be less efficient than generic collections, such as <span class="spanHT">List&lt;T&gt;</span>, due to boxing and unboxing of value types and the lack of type safety.</li>
</ul>



<p class="p-mb-0"><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"><strong>Note:</strong></mark> It is generally recommended to use generic collections, such as <span class="spanHT">List&lt;T></span>, which provide type safety and better performance.</p>



<button class="shbtn" id="shbtn18246" onclick="showHideBlock(18246)">&#9660; <u>Show example</u></button>
<div id="shdiv18246" style="display: none;">
<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Collections;

<span class="key">public</span> <span class="key">class</span> Example
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span style="background:#f2f19d;"><span class="custkey"><b>ArrayList</b></span> arrayList = <span class="key">new</span> <span class="custkey"><b>ArrayList</b></span>();</span>

        <span class="com">// Adding elements</span>
        arrayList.Add(1);
        arrayList.Add(<span class="str">"Hello"</span>);
        arrayList.Add(3.14);

        <span class="com">// Accessing elements</span>
        Console.WriteLine(arrayList[0]); <span class="com">// Output: 1</span>
        Console.WriteLine(arrayList[1]); <span class="com">// Output: Hello</span>
        Console.WriteLine(arrayList[2]); <span class="com">// Output: 3.14</span>

        <span class="com">// Removing elements</span>
        arrayList.Remove(1);

        <span class="com">// Iterating through the ArrayList</span>
        <span class="key">foreach</span> (<span class="key">var</span> item <span class="key">in</span> arrayList)
        {
            Console.WriteLine(item);
        }
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is List? When to use?</strong></h3>



<p class="custp1">A <strong>List</strong> in C# is a generic collection that can store elements of a specific type, providing type safety &amp; preventing runtime type errors, and providing dynamic resizing. It is part of the <span class="spanHT">System.Collections.Generic</span> namespace</p>



<p class="custp1 p-mb-0"><strong><em>When to Use:</em></strong> </p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>Use <span class="spanHT">List&lt;T&gt;</span> when you need to ensure that all elements in the collection are of the same type, providing compile-time type checking and reducing runtime errors.</li>



<li>When you need efficient random access to elements, as well as efficient resizing and insertion/removal operations.</li>
</ul>



<button class="shbtn" id="shbtn16696" onclick="showHideBlock(16696)">&#9660; <u>Show example</u></button>
<div id="shdiv16696" style="display: none;">
<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Collections.Generic;

<span class="key">public</span> <span class="key">class</span> Example
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Creating a list of integers</span>
        <span style="background:#f2f19d;"><span class="custkey"><b>List</b></span>&lt;<span class="key">int</span>&gt list = <span class="key">new</span> <span class="custkey"><b>List</b></span>&lt;<span class="key">int</span>&gt();</span>

        <span class="com">// Adding elements</span>
        list.Add(1);
        list.Add(2);
        list.Add(3);

        <span class="com">// Accessing elements</span>
        Console.WriteLine(list[0]); <span class="com">// Output: 1</span>
        Console.WriteLine(list[1]); <span class="com">// Output: 2</span>
        Console.WriteLine(list[2]); <span class="com">// Output: 3</span>

        <span class="com">// Removing elements</span>
        list.Remove(1);

        <span class="com">// Iterating through the List</span>
        <span class="key">foreach</span> (<span class="key">var</span> item <span class="key">in</span> list)
        {
            Console.WriteLine(item);
        }
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference between ArrayList and List.</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th></th>
            <th>ArrayList</th>
            <th>List&lt;T&gt;</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Type Safety</th>
            <td>No (can store any type)</td>
            <td>Yes (stores elements of a specified type)</td>
        </tr>
        <tr>
            <th>Performance</th>
            <td>Potential boxing/unboxing issues with value types</td>
            <td>No boxing/unboxing, better performance with value types</td>
        </tr>
        <tr>
            <th>Generic</th>
            <td>No</td>
            <td>Yes</td>
        </tr>
        <tr>
            <th>Initialization</th>
            <td>ArrayList arrayList = new ArrayList();</td>
            <td>List&lt;int&gt; list = new List&lt;int&gt;();</td>
        </tr>
        <tr>
            <th>Namespace</th>
            <td>System.Collections</td>
            <td>System.Collections.Generic</td>
        </tr>
        <tr>
            <th>Usage</th>
            <td>Legacy code, non-type safe scenarios</td>
            <td>Modern C# development, type-safe scenarios</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference between Array and List&lt;T&gt;.</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th>Array</th>
            <th>List&lt;T&gt;</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Fixed size, defined at initialization</td>
            <td>Dynamic size, can grow or shrink</td>
        </tr>
        <tr>
            <td>Supports both reference and value types</td>
            <td>Generic, supports any type T</td>
        </tr>
        <tr>
            <td>Faster for fixed-size operations</td>
            <td>Slightly slower due to resizing operations</td>
        </tr>
        <tr>
            <td>Contiguous block of memory</td>
            <td>Allocates more memory as needed</td>
        </tr>
        <tr>
            <td>Less flexible due to fixed size</td>
            <td>More flexible with dynamic resizing</td>
        </tr>
        <tr>
            <td>Limited built-in methods (e.g., Length, CopyTo)</td>
            <td>Rich set of methods (e.g., Add, Remove, Find)</td>
        </tr>
        <tr>
            <td>Simple, direct initialization</td>
            <td>Initialization Requires specifying type, more verbose</td>
        </tr>
        <tr>
            <td>Direct element access via index</td>
            <td>Direct element access via index</td>
        </tr>
        <tr>
            <td>Good for scenarios where size is constant and known</td>
            <td>Ideal for scenarios where size changes dynamically</td>
        </tr>
        <tr>
            <td>Limited LINQ support</td>
            <td>Extensive support for LINQ queries</td>
        </tr>
    </tbody>
</table>
<br>



<p class="p-mb-0"><strong><em>Array example:</em></strong></p>



<pre class="pchl"><code><span class="key">int</span>[] numbers = <span class="key">new int</span>[5] { 1, 2, 3, 4, 5 };
<span class="com">// Fixed size, can't add or remove elements</span></code></pre>
<br>



<p class="p-mb-0"><strong><em>List&lt;T&gt; example:</em></strong></p>



<pre class="pchl"><code><span class="custkey">List</span>&lt;<span class="key">int</span>&gt numbers = <span class="key">new</span> <span class="custkey">List</span>&lt;<span class="key">int</span>&gt { 1, 2, 3, 4, 5 };
numbers.Add(6); <span class="com">// Can add more elements dynamically</span></code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is HashTable? When to use?</strong></h3>



<p class="custp1 p-mb-0">A <strong>Hashtable</strong> in C# is a collection that stores key-value pairs. It is part of the <span class="spanHT">System.Collections</span> namespace and allows for fast retrieval of values (Fast Lookups) based on their keys. The keys in a Hashtable must be unique, and each key is associated with exactly one value. Can store keys and values of any type, but does not provide type safety at compile time. Dynamically resizes to accommodate the number of elements.</p>



<p class="custp1 p-mb-0"><strong><em>When to Use:</em></strong> </p>



<ul class="ol1 wp-block-list">
<li>When you need to store data as <em>key-value pairs</em> for quick retrieval based on the key.</li>



<li>When maintaining or working with <em>legacy </em>code that uses Hashtable.</li>



<li>When dealing with relatively <em>small collections</em> where the non-generic nature and potential boxing/unboxing overhead are not significant issues.</li>
</ul>



<p class="p-mb-0"><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"><strong>Note:</strong></mark> It is generally recommended to use the generic <span class="spanHT">Dictionary&lt;TKey, TValue></span> collection, which provides type safety and better performance.</p>



<button class="shbtn" id="shbtn55943" onclick="showHideBlock(55943)">&#9660; <u>Show example</u></button>
<div id="shdiv55943" style="display: none;">
<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Collections;

<span class="key">public</span> <span class="key">class</span> Example
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Creating a Hashtable</span>
        <span style="background:#f2f19d;"><span class="custkey"><b>Hashtable</b></span> hashtable = <span class="key">new</span> <span class="custkey"><b>Hashtable</b></span>();</span>

        <span class="com">// Adding key-value pairs</span>
        hashtable.Add(<span class="str">"one"</span>, 1);
        hashtable.Add(<span class="str">"two"</span>, 2);
        hashtable.Add(<span class="str">"three"</span>, 3);

        <span class="com">// Accessing elements by key</span>
        Console.WriteLine(hashtable[<span class="str">"one"</span>]);   <span class="com">// Output: 1</span>
        Console.WriteLine(hashtable[<span class="str">"two"</span>]);   <span class="com">// Output: 2</span>

        <span class="com">// Iterating through the Hashtable</span>
        <span class="key">foreach</span> (DictionaryEntry entry <span class="key">in</span> hashtable)
        {
            Console.WriteLine($<span class="str">"{entry.Key}: {entry.Value}"</span>);
        }

        <span class="com">// Checking if a key exists</span>
        <span class="key">if</span> (hashtable.ContainsKey(<span class="str">"three"</span>))
        {
            Console.WriteLine(<span class="str">"Key 'three' exists."</span>);
        }

        <span class="com">// Removing a key-value pair</span>
        hashtable.Remove(<span class="str">"two"</span>);
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Dictionary? When to use?</strong></h3>



<p class="custp1 p-mb-0">A <strong>Dictionary</strong> in C# is a generic collection that stores key-value pairs. It is part of the <span class="spanHT">System.Collections.Generic</span> namespace and provides a fast way to look up values based on their keys. The keys in a Dictionary must be unique, and each key is associated with exactly one value.</p>



<p class="custp1 p-mb-0"><strong><em>When to Use:</em></strong> When you want to ensure that all keys and values are of specific types, providing compile-time type checking and need to store data as key-value pairs for quick retrieval based on the key.</p>



<button class="shbtn" id="shbtn73228" onclick="showHideBlock(73228)">&#9660; <u>Show example</u></button>
<div id="shdiv73228" style="display: none;">
<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Collections.Generic;

<span class="key">public</span> <span class="key">class</span> Example
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Creating a Dictionary</span>
        <span style="background:#f2f19d;"><span class="custkey"><b>Dictionary</b></span>&lt;<span class="key">string</span>, <span class="key">int</span>&gt dictionary = <span class="key">new</span> <span class="custkey"><b>Dictionary</b></span>&lt;<span class="key">string</span>, <span class="key">int</span>&gt();</span>

        <span class="com">// Adding key-value pairs</span>
        dictionary.Add(<span class="str">"one"</span>, 1);
        dictionary.Add(<span class="str">"two"</span>, 2);
        dictionary.Add(<span class="str">"three"</span>, 3);

        <span class="com">// Accessing elements by key</span>
        Console.WriteLine(dictionary[<span class="str">"one"</span>]);   <span class="com">// Output: 1</span>
        Console.WriteLine(dictionary[<span class="str">"two"</span>]);   <span class="com">// Output: 2</span>

        <span class="com">// Iterating through the Dictionary</span>
        <span class="key">foreach</span> (<span class="key">var</span> kvp <span class="key">in</span> dictionary)
        {
            Console.WriteLine($<span class="str">"{kvp.Key}: {kvp.Value}"</span>);
        }

        <span class="com">// Checking if a key exists</span>
        <span class="key">if</span> (dictionary.ContainsKey(<span class="str">"three"</span>))
        {
            Console.WriteLine(<span class="str">"Key 'three' exists."</span>);
        }

        <span class="com">// Removing a key-value pair</span>
        dictionary.Remove(<span class="str">"two"</span>);
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference between HashTable and Dictionary.</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th></th>
            <th>Hashtable</th>
            <th>Dictionary&lt;TKey, TValue&gt;</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Type Safety</th>
            <td>No (can store any type)</td>
            <td>Yes (stores elements of specified key and value types)</td>
        </tr>
        <tr>
            <th>Performance</th>
            <td>Potential boxing/unboxing issues with value types</td>
            <td>No boxing/unboxing, better performance with value types</td>
        </tr>
        <tr>
            <th>Generic</th>
            <td>No</td>
            <td>Yes</td>
        </tr>
        <tr>
            <th>Initialization</th>
            <td>Hashtable hashtable = new Hashtable();</td>
            <td>Dictionary&lt;string, int&gt; dictionary = new Dictionary&lt;string, int&gt;();</td>
        </tr>
        <tr>
            <th>Namespace</th>
            <td>System.Collections</td>
            <td>System.Collections.Generic</td>
        </tr>
        <tr>
            <th>Usage</th>
            <td>Legacy code, non-type safe scenarios</td>
            <td>Modern C# development, type-safe scenarios</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement a ConcurrentDictionary in C#?</strong></h3>



<p class="custp1 p-mb-0"><strong>ConcurrentDictionary</strong> provides a thread-safe collection that allows multiple threads to concurrently add, update, or remove items from the dictionary without requiring manual synchronization, such as using locks.</p>



<pre class="pchl"><code>ConcurrentDictionary&lt;<span class="key">int</span>, <span class="key">string</span>&gt dictionary = <span class="key">new</span> ConcurrentDictionary&lt;<span class="key">int</span>, <span class="key">string</span>&gt();</code></pre>



<button class="shbtn" id="shbtn22944" onclick="showHideBlock(22944)">&#9660; <u>Show example</u></button>
<div id="shdiv22944" style="display: none;">

<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Collections.Concurrent;

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Create a ConcurrentDictionary</span>
        <span style="background:#f2f19d;">ConcurrentDictionary&lt;<span class="key">int</span>, <span class="key">string</span>&gt</span> dictionary = <span class="key">new</span> <span style="background:#f2f19d;">ConcurrentDictionary&lt;<span class="key">int</span>, <span class="key">string</span>&gt()</span>;

        <span class="com">// Add elements</span>
        dictionary.TryAdd(1, <span class="str">"One"</span>);
        dictionary.TryAdd(2, <span class="str">"Two"</span>);

        <span class="com">// Access and update elements</span>
        <span class="key">string</span> value = dictionary.GetOrAdd(3, <span class="str">"Three"</span>);
        dictionary.AddOrUpdate(2, <span class="str">"Two"</span>, (key, oldValue) =&gt <span class="str">"UpdatedTwo"</span>);

        <span class="com">// Remove an element</span>
        <span class="key">bool</span> removed = dictionary.TryRemove(1, <span class="key">out</span> <span class="key">string</span> removedValue);

        <span class="com">// Output the dictionary contents</span>
        <span class="key">foreach</span> (<span class="key">var</span> kvp <span class="key">in</span> dictionary)
        {
            Console.WriteLine($<span class="str">"Key: {kvp.Key}, Value: {kvp.Value}"</span>);
        }
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Enum in C#?</strong></h3>



<p class="custp1 p-mb-0">An <strong>enum</strong> (short for &#8220;enumeration&#8221;) in C# is a value type that allows you to define a group of named constants. Enums are useful for <strong><em>representing a collection/group of related values</em></strong>, making your code more readable and maintainable by providing meaningful names to those values instead of using random numeric values. </p>



<p class="custp1 p-mb-0">The default type of enum is <span class="spanHT">int</span>. Enums are strongly typed, ensuring compile-time type safety. You cannot create an instance of an enum using the <span class="spanHT">new</span> keyword (Cannot Be Instantiated).</p>



<p class="custp1 p-mb-0">The members of an enum are accessed in a static-like manner, meaning you do not create an instance of the enum to access its values. </p>



<p class="custp1 p-mb-0"><strong><em>When to Use:</em></strong> When you need to define a group of related constants, such as days of the week, error codes, or status codes.</p>



<button class="shbtn" id="shbtn20577" onclick="showHideBlock(20577)">&#9660; <u>Show example</u></button>
<div id="shdiv20577" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Defining an Enum</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key" style="background:#f2f19d;">enum</span> DaysOfWeek
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>Using an Enum</b></div>
<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">public</span> <span class="key">class</span> Example
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Assigning an enum value to a variable</span>
        DaysOfWeek today = <span style="background:#f2f19d;">DaysOfWeek.Monday</span>;

        <span class="com">// Checking an enum value</span>
        <span class="key">if</span> (today == DaysOfWeek.Monday)
        {
            Console.WriteLine(<span class="str">"Today is Monday."</span>);
        }

        <span class="com">// Using an enum in a switch statement</span>
        <span class="key">switch</span> (today)
        {
            <span class="key">case</span> DaysOfWeek.Sunday:
                Console.WriteLine(<span class="str">"Today is Sunday."</span>);
                break;
            <span class="key">case</span> DaysOfWeek.Monday:
                Console.WriteLine(<span class="str">"Today is Monday."</span>);
                break;
            <span class="com">// Other cases...</span>
            default:
                Console.WriteLine(<span class="str">"Today is another day."</span>);
                break;
        }

        <span class="com">// Getting the underlying value of an enum</span>
        <span class="key">int</span> dayValue = (<span class="key">int</span>)today;
        Console.WriteLine($<span class="str">"The numeric value of {today} is {dayValue}."</span>);
    }
} </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>Custom Underlying Type</b></div>
<pre class="pchl"><code><span class="key">public</span> <span style="background:#f2f19d;"><span class="key">enum</span> HttpStatusCode : <span class="key">short</span></span>
{
    OK = 200,
    Created = 201,
    Accepted = 202,
    NoContent = 204,
    BadRequest = 400,
    Unauthorized = 401,
    Forbidden = 403,
    NotFound = 404
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are partial classes in C#?</strong></h3>



<p class="custp1 p-mb-0">Partial classes allow a class definition to be split across multiple files and each part must use the <span class="spanHT">partial</span> keyword. This can be particularly useful for organizing large classes or when working with auto-generated code, where you might want to separate the generated code from your custom code (Separation of Concerns).</p>



<p class="custp1 p-mb-0">All parts of the partial class must be defined in the same assembly and namespace.</p>



<p class="custp1 p-mb-0">All parts of the partial class are combined into a single class when the application is compiled.</p>



<button class="shbtn" id="shbtn69749" onclick="showHideBlock(69749)">&#9660; <u>Show example</u></button>
<div id="shdiv69749" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>File 1: Person.Part1.cs</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key" style="background:#f2f19d;">partial</span> <span class="key">class</span> Person
{
    <span class="key">public</span> <span class="key">string</span> FirstName { get; set; }
    <span class="key">public</span> <span class="key">string</span> LastName { get; set; }

    <span class="key">public</span> <span class="key">void</span> PrintFullName()
    {
        Console.WriteLine($<span class="str">"{FirstName} {LastName}"</span>);
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>File 2: Person.Part2.cs</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key" style="background:#f2f19d;">partial</span> <span class="key">class</span> Person
{
    <span class="key">public</span> <span class="key">int</span> Age { get; set; }

    <span class="key">public</span> <span class="key">void</span> PrintAge()
    {
        Console.WriteLine($<span class="str">"Age: {Age}"</span>);
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Combined Usage</b></div>
<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">public</span> <span class="key">class</span> Example
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="custkey">Person</span> person = <span class="key">new</span> <span class="custkey">Person</span>
        {
            FirstName = <span class="str">"John"</span>,
            LastName = <span class="str">"Doe"</span>,
            Age = 30
        };

        person.PrintFullName();  <span class="com">// Output: John Doe</span>
        person.PrintAge();       <span class="com">// Output: Age: 30</span>
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a partial method in C#?</strong></h3>



<p class="custp1 p-mb-0">A partial method in C# is a method that is declared in one part of a partial class or struct and optionally implemented in another part. Partial methods enable developers to define method signatures within a class, allowing other parts of the class to provide the implementation or leave it empty. If the method is not implemented, the compiler removes its declaration and calls, resulting in no performance penalty.</p>



<p class="custp1 p-mb-0"><strong><em>Restrictions or Limitations:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>Partial methods must return <span class="spanHT">void</span>.</li>



<li>They cannot have access modifiers; they are implicitly <span class="spanHT">private</span>.</li>



<li>They cannot be <span class="spanHT">extern</span>, <span class="spanHT">virtual</span>, <span class="spanHT">abstract</span>, <span class="spanHT">override</span>, or <span class="spanHT">static</span>.</li>
</ul>



<button class="shbtn" id="shbtn53872" onclick="showHideBlock(53872)">&#9660; <u>Show example</u></button>
<div id="shdiv53872" style="display: none;">

<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">public <b>partial class</b></span> MyClass
{
    <span class="com">// Declaration of a partial method</span>
    <span style="background:#f2f19d;"><span class="key">partial void</span> OnMessageLogged(<span class="key">string</span> message);</span>

    <span class="key">public</span> <span class="key">void</span> LogMessage(<span class="key">string</span> message)
    {
        Console.WriteLine(<span class="str">"Logging message: "</span> + message);
		
        <span class="com">// Call to the partial method</span>
        <span style="background:#f2f19d;">OnMessageLogged(message)</span>; 
    }
}

<span class="com">// Another part of the partial class</span>
<span class="key">public <b>partial class</b></span> MyClass
{
    <span class="com">// Implementation of the partial method</span>
    <span style="background:#f2f19d;"><span class="key">partial void</span> OnMessageLogged(<span class="key">string</span> message)</span>
    {
        Console.WriteLine(<span class="str">"Message logged: "</span> + message);
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        MyClass myClass = <span class="key">new</span> MyClass();
        myClass.LogMessage(<span class="str">"Hello, World!"</span>);
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Synchronous vs. Asynchronous Operations in C#</strong></h3>



<p class="custp1 p-mb-0"><strong>Synchronous operations</strong> are operations that run sequentially. Each operation must complete before the next one starts. The program execution waits for the current operation to finish before moving to the next operation. </p>



<p class="custp1 p-mb-0"><strong>Asynchronous operations</strong> allow a program to initiate an operation and then move on to other tasks without waiting for the operation to complete. The program can continue running other tasks, and the operation will complete at some point in the future.</p>



<button class="shbtn" id="shbtn25808" onclick="showHideBlock(25808)">&#9660; <u>Show example</u></button>
<div id="shdiv25808" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Synchronous Operation Example</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> SynchronousExample
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        Console.WriteLine(<span class="str">"Starting synchronous operation..."</span>);
        PerformSynchronousOperation();
        Console.WriteLine(<span class="str">"Synchronous operation completed."</span>);
    }

    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> PerformSynchronousOperation()
    {
        <span class="com">// Simulate a time-consuming operation</span>
        System.Threading.Thread.Sleep(2000); <span class="com">// Sleep for 2 seconds</span>
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Asynchronous Operation Example</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> AsynchronousExample
{
    <span class="key">public</span> <span class="key">static</span> <span class="key" style="background:#f2f19d;">async</span> Task Main()
    {
        Console.WriteLine(<span class="str">"Starting asynchronous operation..."</span>);
        <span class="key">await</span> PerformAsynchronousOperation();
        Console.WriteLine(<span class="str">"Asynchronous operation completed."</span>);
    }

    <span class="key">public</span> <span class="key">static</span> <span class="key" style="background:#f2f19d;">async</span> Task PerformAsynchronousOperation()
    {
        <span class="com">// Simulate a time-consuming operation</span>
        <span class="key">await</span> Task.Delay(2000); <span class="com">// Delay for 2 seconds</span>
    }
} </code></pre>


</div>



<br><br><br>
<table>
    <thead>
        <tr>
            <th>Synchronous</th>
            <th>Asynchronous</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Sequential, one operation at a time</td>
            <td>Concurrent, multiple operations can overlap</td>
        </tr>
        <tr>
            <td>Blocks the calling thread</td>
            <td>Does not block the calling thread</td>
        </tr>
        <tr>
            <td>Simpler to implement and understand</td>
            <td>More complex due to callbacks, continuations, etc.</td>
        </tr>
        <tr>
            <td>Suitable for CPU-bound tasks</td>
            <td>Suitable for I/O-bound or long-running tasks</td>
        </tr>
        <tr>
            <td>Can cause the application to become unresponsive</td>
            <td>Improves application responsiveness, especially for I/O-bound tasks</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Serialization and Deserialization in C#?</strong></h3>



<p class="custp1 p-mb-0"><strong>Serialization</strong> is the process of converting an object into a format that can be easily stored or transmitted, such as JSON, XML, or binary. </p>



<p class="custp1 p-mb-0"><strong>Deserialization</strong> is the process of converting the serialized data back into an object. </p>



<p class="custp1 p-mb-0">In C#, serialization and deserialization are commonly used when working with data exchange, file storage, or communication between applications. The .NET framework provides built-in classes such as <span class="spanHT">JsonSerializer</span>, <span class="spanHT">XmlSerializer</span>, and <span class="spanHT">BinaryFormatter</span> for these purposes.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are extension methods in C#?</strong></h3>



<p class="custp1 p-mb-0"><strong>Extension methods</strong> are a special kind of static method in C# that allows you to add new methods to existing types without modifying the original type or creating a new derived type. Defined as static methods in static classes and called as if they were instance methods. It Improves readability, reusability, and maintainability of code. It Cannot access private members.</p>



<p class="custp1 p-mb-0">The first parameter specifies which type the method operates on, and it is preceded by the <span class="spanHT">this</span> keyword. </p>



<p class="custp1 p-mb-0"><strong><em>Best Practices:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Use carefully</strong>: Don&#8217;t overuse extension methods. They should enhance readability and maintainability, not complicate the codebase.</li>



<li><strong>Naming</strong>: <strong>1)</strong> Choose method names that clearly convey their purpose and match the naming conventions of the extended type. <strong>2)</strong> If multiple extension methods with the same name and signature are available, it can cause naming conflicts.</li>



<li><strong>Namespaces</strong>: Place extension methods in appropriate namespaces and use <span class="spanHT">using</span> directives to include them only where needed.</li>
</ul>



<button class="shbtn" id="shbtn75399" onclick="showHideBlock(75399)">&#9660; <u>Show example</u></button>
<div id="shdiv75399" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Define an Extension Method</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">static</span> <span class="key">class</span> StringExtensions
{
    <span class="key">public</span> <span class="key" style="background:#f2f19d;">static</span> <span class="key">string</span> CapitalizeFirstLetter(<span class="key" style="background:#f2f19d;">this</span> <span class="key">string</span> input)
    {
        <span class="key">if</span> (string.IsNullOrEmpty(input))
            <span class="key">return</span> input;

        <span class="key">return</span> char.ToUpper(input[0]) + input.Substring(1);
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Using the Extension Method</b></div>
<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">public</span> <span class="key">class</span> Example
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">string</span> example = <span class="str">"hello world"</span>;
        <span class="key">string</span> capitalized = example.<span style="background:#f2f19d;">CapitalizeFirstLetter()</span>; <span class="com">// Using the extension method</span>

        Console.WriteLine(capitalized); <span class="com">// Output: Hello world</span>
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of &#8216;using&#8217; statement</strong> <strong>in C#?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT"><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/using" target="_blank" rel="noopener"><span class="cLink3">using</span></a></span> statement ensures proper <em>disposal of resources</em> that implement <span class="spanHT">IDisposable</span> and when they are no longer needed, e.g., unmanaged resources like file handles, database connections, and network connections.</p>



<button class="shbtn" id="shbtn15687" onclick="showHideBlock(15687)">&#9660; <u>Show example</u></button>
<div id="shdiv15687" style="display: none;">

<pre class="pchl"><code><span class="com">// 1) Namespaces</span>
<span class="key" style="background:#f2f19d;">using</span> System;
<span class="key" style="background:#f2f19d;">using</span> System.IO;

<span class="key">public</span> <span class="key">class</span> Example
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// 2) Ensure the StreamReader is disposed of correctly</span>
        <span class="key" style="background:#f2f19d;">using</span> (<span class="custkey">StreamReader</span> reader = <span class="key">new</span> <span class="custkey">StreamReader</span>(<span class="str">"example.txt"</span>))
        {
            <span class="key">string</span> content = reader.ReadToEnd();
            Console.WriteLine(content);
        } <span class="com">// StreamReader.Dispose is called automatically here</span>
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use the &#8216;using&#8217; directive to manage namespaces?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">using</span> directive simplifies referencing types from namespaces. It allows you to avoid fully qualifying type names, manage scope, create aliases for namespaces or types, and import static members for direct access. It is typically placed at the top of a file.</p>



<br>
<ol class="ol1 ol1-mb-0">

<li><strong>Simplify Code</strong>: Avoids writing fully qualified names.</li>
<button class="shbtn" id="shbtn83123" onclick="showHideBlock(83123)">&#9660; <u>Show example</u></button>
<div id="shdiv83123" style="display: none;">
<pre class="pchl"><code><span class="key" style="background:#f2f19d;">using</span> System;

<span class="key">namespace</span> Example
{
    <span class="key">class</span> Program
    {
        <span class="com">// ...</span>
    }
} </code></pre>
</div>


<li class="custp1"><strong>Aliases</strong>: Creates shortcuts for namespaces or types.</li>
<button class="shbtn" id="shbtn83108" onclick="showHideBlock(83108)">&#9660; <u>Show example</u></button>
<div id="shdiv83108" style="display: none;">
<pre class="pchl"><code><span style="background:#f2f19d;"><span class="key">using</span> ProjectAlias =</span> MyProject.LongNamespace;
<span style="background:#f2f19d;"><span class="key">using</span> AliasExample =</span> System.Collections.Generic.List&lt;<span class="key">string</span>&gt; </code></pre>
</div>


<li class="custp1"><strong>Static Using</strong>: Imports static members for easier access.</li>
<button class="shbtn" id="shbtn58494" onclick="showHideBlock(58494)">&#9660; <u>Show example</u></button>
<div id="shdiv58494" style="display: none;">
<pre class="pchl"><code><span class="key" style="background:#f2f19d;">using static</span> System.Math;

<span class="key">namespace</span> Example
{
    <span class="key">class</span> Program
    {
        <span class="com">// ...</span>
    }
} </code></pre>
</div>


<li class="custp1"><strong>Scope Management</strong>: Can be placed at the file, namespace, or class level to control scope.</li>
<button class="shbtn" id="shbtn88218" onclick="showHideBlock(88218)">&#9660; <u>Show example</u></button>
<div id="shdiv88218" style="display: none;">
<pre class="pchl"><code><span class="key">namespace</span> Example
{
    <span class="key" style="background:#f2f19d;">using</span> System.Text;

    <span class="key">class</span> Program
    {
        <span class="com">// ...</span>
    }
} </code></pre>
</div>

</ol>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the &#8216;default&#8217; keyword in C#?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">default</span> keyword is used in several contexts to provide a default value for a type or to specify a default case in a <span class="spanHT">switch</span> statement. Its purpose varies based on the context in which it is used.</p>



<pre class="pchl"><code><span class="com">// Syntax</span>
T defaultValue = <span class="key">default</span>(T); </code></pre><br>



<p class="custp1 p-mb-0"><strong>1) Default Value for a Type</strong>: Used to obtain the default value of a type, especially useful in generics.</p>



<pre class="pchl"><code><span class="key">int</span> defaultInt = <span class="key" style="background:#f2f19d;">default</span>(<span class="key">int</span>); <span class="com">// 0</span> </code></pre><br>



<p class="custp1 p-mb-0"><strong>2) Default Case in a Switch Statement</strong>: Specifies a case to execute when no other case matches.</p>



<pre class="pchl"><code><span class="key">switch</span> (expression)
{
    <span class="key">case</span> value1:
        <span class="com">// Code block</span>
        break;
    <span class="key" style="background:#f2f19d;">default:</span>
        <span class="com">// Code block</span>
        break;
} </code></pre><br>



<p class="custp1 p-mb-0"><strong>3) Default Literal</strong>: A shorthand way to obtain the default value of a type (C# 7.1 and later).</p>



<pre class="pchl"><code><span class="key">int</span> defaultInt = <span class="key" style="background:#f2f19d;">default</span>; <span class="com">// 0</span> </code></pre>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the &#8216;default&#8217; literal in generic programming?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">default</span> literal is used to provide a default value for generic types. It helps in <strong><em>initializing</em></strong> generic variables with a default value. Useful in generic methods to <strong><em>return</em></strong> default values for type parameters.</p>



<button class="shbtn" id="shbtn55775" onclick="showHideBlock(55775)">&#9660; <u>Show example</u></button>
<div id="shdiv55775" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1) Using default to Initialize a generic variable:</b></div>

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> GenericClass&lt;T&gt
{
    <span class="key">private</span> T _value;

    <span class="key">public</span> GenericClass()
    {
        <span class="com">// Initialize the value with the default value of type T</span>
        _value = <span class="key"  style="background:#f2f19d;">default</span>;
    }

    <span class="key">public</span> T GetValue()
    {
        <span class="key">return</span> _value;
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Create an instance of GenericClass for int</span>
        <span class="key">var</span> intInstance = <span style="background:#f2f19d;"><span class="key">new</span> GenericClass&lt;<span class="key">int</span>&gt()</span>;
        Console.WriteLine(intInstance.GetValue()); <span class="com">// Output: 0</span>

        <span class="com">// Create an instance of GenericClass for string</span>
        <span class="key">var</span> stringInstance = <span style="background:#f2f19d;"><span class="key">new</span> GenericClass&lt;<span class="key">string</span>&gt()</span>;
        Console.WriteLine(stringInstance.GetValue() == <span class="key">null</span>); <span class="com">// Output: True</span>
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2) Returning Default Value in Generic Methods:</b></div>

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Utility
{
    <span class="key">public</span> <span class="key">static</span> T GetDefaultValue&lt;T&gt()
    {
        <span class="key">return <span style="background:#f2f19d;">default</span></span>;
    }
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">int</span> defaultInt = <span style="background:#f2f19d;">Utility.GetDefaultValue&lt;<span class="key">int</span>&gt()</span>;
        Console.WriteLine(defaultInt); <span class="com">// Output: 0</span>

        <span class="key">string</span> defaultString = <span style="background:#f2f19d;">Utility.GetDefaultValue&lt;<span class="key">string</span>&gt()</span>;
        Console.WriteLine(defaultString == <span class="key">null</span>); <span class="com">// Output: True</span>
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the use of the yield keyword in C#?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">yield</span> keyword in C# is used in an iterator to provide a value to the enumerator object or to signal the end of the iteration. It simplifies the implementation of custom iteration over collections.</p>



<p class="custp1 p-mb-0"><strong><em>Uses of the &#8216;yield&#8217; Keyword:</em></strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><span class="spanHT">yield return</span>: Provides the next value in the iteration.</li>



<li><span class="spanHT">yield break</span>: Ends the iteration.</li>
</ol>



<p class="custp1 p-mb-0"><strong><em>Benefits:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Simplifies Code</strong>: Reduces the complexity of writing custom iterators.</li>



<li><strong>Lazy Evaluation</strong>: Values are generated on demand.</li>



<li><strong>Maintains State</strong>: Automatically maintains the state of the iteration across multiple calls.</li>
</ul>



<button class="shbtn" id="shbtn6301" onclick="showHideBlock(6301)">&#9660; <u>Show example</u></button>
<div id="shdiv6301" style="display: none;">

<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Collections.Generic;

<span class="key">public</span> <span class="key">class</span> Numbers
{
    <span class="key">public</span> IEnumerable&lt;<span class="key">int</span>&gt GetNumbers(<span class="key">int</span> max)
    {
        <span class="key">for</span> (<span class="key">int</span> i = 0; i &lt;= max; i++)
        {
            <span class="key">if</span> (i &gt 5)
                <span class="key" style="background:#f2f19d;">yield break</span>; <span class="com">// Stop the iteration if i is greater than 5</span>
            <span class="key" style="background:#f2f19d;">yield return</span> i;
        }
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">var</span> numbers = <span class="key">new</span> Numbers();
        <span class="key">foreach</span> (<span class="key">int</span> number <span class="key">in</span> numbers.GetNumbers(10))
        {
            Console.WriteLine(number);
        }
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement an iterator in C#?</strong></h3>



<p class="custp1 p-mb-0">Iterators are methods, properties, or indexers that perform custom iteration over a collection. iterator is implemented using the <span class="spanHT">yield return</span> and <span class="spanHT">yield break</span> statements.</p>



<button class="shbtn" id="shbtn87821" onclick="showHideBlock(87821)">&#9660; <u>Show example</u></button>
<div id="shdiv87821" style="display: none;" class="shdt">

<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Collections;
<span class="key">using</span> System.Collections.Generic;

<span class="com">// Implements IEnumerable<int> to allow iteration over the collection.</span>
<span class="key">public</span> <span class="key">class</span> NumberCollection : IEnumerable&lt;<span class="key">int</span>&gt
{
    <span class="key">private</span> int[] numbers = { 1, 2, 3, 4, 5 };

    <span class="key">public</span> IEnumerator&lt;<span class="key">int</span>&gt GetEnumerator()
    {
        <span class="key">foreach</span> (<span class="key">int</span> number <span class="key">in</span> numbers)
        {
            <span class="key" style="background:#f2f19d;">yield return</span> number;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        <span class="key">return</span> GetEnumerator();
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        NumberCollection collection = <span class="key">new</span> NumberCollection();

        <span class="key">foreach</span> (<span class="key">int</span> number <span class="key">in</span> collection)
        {
            Console.WriteLine(number);
        }
    }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">
Uses <b>yield return</b> to return each element in the collection one by one.<br>
Implements the <b>GetEnumerator</b> method from <b>IEnumerable<int></b> interface.
</div>

</div>
<br><br>



<p class="p-mb-0"><strong><em>When to use iterator:</em></strong></p>



<ul class="ol1 wp-block-list">
<li class="custp1"><strong>Custom Collection</strong>: You have a custom collection that you want to iterate over in a specific way.</li>



<li><strong>Lazy Evaluation</strong>: You want to yield items one at a time as they are needed, rather than generating all items at once.</li>



<li><strong>Complex Iteration Logic</strong>: The iteration logic is complex and involves multiple steps or conditions.</li>
</ul>



<p class="p-mb-0">Suppose you have a tree data structure, and you want to iterate over its nodes in a specific order (e.g., depth-first search).</p>



<button class="shbtn" id="shbtn47615" onclick="showHideBlock(47615)">&#9660; <u>Show example</u></button>
<div id="shdiv47615" style="display: none;">

<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Collections;
<span class="key">using</span> System.Collections.Generic;

<span class="key">public</span> <span class="key">class</span> TreeNode&lt;T&gt
{
    <span class="key">public</span> T Value { get; set; }
    <span class="key">public</span> List&lt;TreeNode&lt;T&gt&gt Children { get; } = <span class="key">new</span> List&lt;TreeNode&lt;T&gt&gt();

    <span class="key">public</span> TreeNode(T value)
    {
        Value = value;
    }

    <span class="key">public</span> IEnumerable&lt;T&gt DepthFirstTraversal()
    {
        <span class="key">yield</span> <span class="key">return</span> Value;
        <span class="key">foreach</span> (<span class="key">var</span> child <span class="key">in</span> Children)
        {
            <span class="key">foreach</span> (<span class="key">var</span> descendant <span class="key">in</span> child.DepthFirstTraversal())
            {
                <span class="key">yield</span> <span class="key">return</span> descendant;
            }
        }
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">var</span> root = <span class="key">new</span> TreeNode&lt;<span class="key">int</span>&gt(1);
        root.Children.Add(<span class="key">new</span> TreeNode&lt;<span class="key">int</span>&gt(2));
        root.Children.Add(<span class="key">new</span> TreeNode&lt;<span class="key">int</span>&gt(3));
        root.Children[0].Children.Add(<span class="key">new</span> TreeNode&lt;<span class="key">int</span>&gt(4));
        root.Children[0].Children.Add(<span class="key">new</span> TreeNode&lt;<span class="key">int</span>&gt(5));
        root.Children[1].Children.Add(<span class="key">new</span> TreeNode&lt;<span class="key">int</span>&gt(6));

        <span class="key">foreach</span> (<span class="key">var</span> value <span class="key">in</span> root.DepthFirstTraversal())
        {
            Console.WriteLine(value);
        }
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the &#8216;base&#8217; keyword used for in C#?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">base</span> keyword is used to access members of the base class from within a derived class. It allows derived classes to call methods, access properties, and invoke constructors of their base class.</p>



<p class="custp1 p-mb-0"><strong>Uses of &#8216;base&#8217; Keyword:</strong></p>



<ol class="ol1 ol1-mb-0">

<li><strong>Calling Base Class Constructors</strong>: You can call a constructor of the base class from a constructor of the derived class.</li>
<button class="shbtn" id="shbtn35848" onclick="showHideBlock(35848)">&#9660; <u>Show example</u></button>
<div id="shdiv35848" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> BaseClass
{
    <span class="key">public</span> BaseClass(<span class="key">int</span> number)
    {
        Console.WriteLine($<span class="str">"Base class constructor called with number: {number}"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> DerivedClass : BaseClass
{
    <span class="key">public</span> DerivedClass(<span class="key">int</span> number) : <span class="key" style="background:#f2f19d;">base</span>(number)
    {
        Console.WriteLine($<span class="str">"Derived class constructor called with number: {number}"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        DerivedClass obj = <span class="key">new</span> DerivedClass(10);
    }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">
<b>Output:</b><br>
Base class constructor called with number: 10<br>
Derived class constructor called with number: 10
</div>

</div>


<br><br>
<li><strong>Accessing Base Class Members</strong>: You can access a method, property, indexer, or field of the base class that has been overridden or hidden in the derived class.</li>
<button class="shbtn" id="shbtn5978" onclick="showHideBlock(5978)">&#9660; <u>Show example</u></button>
<div id="shdiv5978" style="display: none;" class="shdt">
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> BaseClass
{
    <span class="key">public</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(<span class="str">"Display method in BaseClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> DerivedClass : BaseClass
{
    <span class="key">public</span> <span class="key">new</span> <span class="key">void</span> Display()
    {
        <span style="background:#f2f19d;">base</span>.Display(); <span class="com">// Calling the base class method</span>
        Console.WriteLine(<span class="str">"Display method in DerivedClass"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        DerivedClass obj = <span class="key">new</span> DerivedClass();
        obj.Display();
    }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">
<b>Output:</b><br>
Display method in BaseClass<br>
Display method in DerivedClass
</div>

</div>

</ol>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you declare and raise an event in C#?</strong></h3>



<p class="custp1 p-mb-0">Events are a way to provide notifications when something occurs. They are commonly used in scenarios where you want to notify other parts of your application about state changes or actions. </p>



<p class="custp1 p-mb-0"><strong><em>Steps to declare and raise event:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>Define a Delegate</li>



<li>Declare the Event</li>



<li>Create a Method to Raise the Event</li>



<li>Raise the Event</li>
</ul>



<button class="shbtn" id="shbtn85760" onclick="showHideBlock(85760)">&#9660; <u>Show example</u></button>
<div id="shdiv85760" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Step-by-Step Implementation:</b><br><br>
<b>1) Define the Delegate</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">delegate</span> <span class="key">void</span> MyEventHandler(<span class="key">object</span> sender, EventArgs e); </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>2) Declare the Event</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> MyClass
{
    <span class="key">public</span> <span class="key">event</span> MyEventHandler MyEvent;

    <span class="key">protected</span> <span class="key">virtual</span> <span class="key">void</span> OnMyEvent(EventArgs e)
    {
        <span class="key">if</span> (MyEvent != <span class="key">null</span>)
        {
            MyEvent(<span class="key">this</span>, e);
        }
    }

    <span class="key">public</span> <span class="key">void</span> TriggerEvent()
    {
        <span class="com">// Raise the event</span>
        OnMyEvent(EventArgs.Empty);
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>3) Subscribe to the Event</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        MyClass myClass = <span class="key">new</span> MyClass();
        myClass.MyEvent += <span class="key">new</span> MyEventHandler(HandleMyEvent);
        myClass.TriggerEvent();
    }

    <span class="key">static</span> <span class="key">void</span> HandleMyEvent(<span class="key">object</span> sender, EventArgs e)
    {
        Console.WriteLine(<span class="str">"Event triggered!"</span>);
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a lambda expression in C#?</strong></h3>



<p class="custp1 p-mb-0">Provide a concise way to define anonymous methods. It allows you to write inline functions that can be passed as arguments to methods. Uses <span class="spanHT">=&gt;</span> operator with parameters on the left and the expression or statements on the right. Commonly used with delegates, LINQ queries, and event handling to simplify code and improve readability.</p>



<button class="shbtn" id="shbtn81387" onclick="showHideBlock(81387)">&#9660; <u>Show example</u></button>
<div id="shdiv81387" style="display: none;">

<br>
<div style="padding-left: 0.3125rem;"><b>Using Lambda Expression with foreach:</b></div>

<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Collections.Generic;

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        List&lt;<span class="key">int</span>&gt numbers = <span class="key">new</span> List&lt;<span class="key">int</span>&gt { 1, 2, 3, 4, 5 };

        <span class="com">// Using a lambda expression in a foreach loop to print each number</span>
        <span style="background:#f2f19d;">numbers.ForEach(number =&gt Console.WriteLine(number));</span>
    }
} </code></pre>


</div>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle exceptions in C#?</strong></h3>



<p class="custp1 p-mb-0">Exceptions are handled using <span class="spanHT">try</span>, <span class="spanHT">catch</span>, <span class="spanHT">finally</span>, and <span class="spanHT">throw</span> keywords. This mechanism helps in managing and responding to runtime errors in a controlled way.</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>try</strong>: Wraps code that might throw an exception.</li>



<li><strong>catch</strong>: Catches and handles exceptions thrown in the <span class="spanHT">try</span> block.</li>



<li><strong>finally</strong>: Contains code that runs after <span class="spanHT">try</span> and <span class="spanHT">catch</span> blocks, regardless of whether an exception was thrown.</li>



<li><strong>throw</strong>: Used to throw an exception manually.</li>
</ul>



<button class="shbtn" id="shbtn46753" onclick="showHideBlock(46753)">&#9660; <u>Show example</u></button>
<div id="shdiv46753" style="display: none;">

<br>
<div style="padding-left: 0.3125rem;"><b>Exception example with multiple Catch Blocks:</b></div>

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Program
{
	<span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
	{
		<span class="key" style="background:#f2f19d;">try</span>
		{
			ValidateNumber(-1);
			DivideNumber(10, 0)
		}
		<span class="key" style="background:#f2f19d;">catch</span> (ArgumentException ex)
		{
			Console.WriteLine(<span class="str">"An error occurred: "</span> + ex.Message);
		}
		<span class="key" style="background:#f2f19d;">catch</span> (DivideByZeroException ex)
		{
			Console.WriteLine(<span class="str">"Cannot divide by zero: "</span> + ex.Message);
		}
		<span class="key" style="background:#f2f19d;">catch</span> (Exception ex)
		{
			Console.WriteLine(<span class="str">"An error occurred: "</span> + ex.Message);
		}
		<span class="key" style="background:#f2f19d;">finally</span>
		{
			Console.WriteLine(<span class="str">"This will always execute."</span>);
		}
	}
	
	<span class="key">public</span> <span class="key">static</span> <span class="key">void</span> ValidateNumber(<span class="key">int</span> number)
	{
		<span class="key">if</span> (number &lt; 0)
		{
			<span class="key" style="background:#f2f19d;">throw</span> <span class="key">new</span> ArgumentException(<span class="str">"Number cannot be negative."</span>);
		}
	}

	<span class="key">public</span> <span class="key">static</span> <span class="key">void</span> DivideNumber(<span class="key">int</span> a, <span class="key">int</span> b)
	{
		<span class="com">// This will throw a DivideByZeroException</span>
		Console.WriteLine(a / b); 
	}
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can I have multiple &#8216;catch&#8217; in exception handling?</strong></h3>



<p class="custp1 p-mb-0">Yes, you can have multiple <span class="spanHT">catch</span> blocks in exception handling. This allows you to handle different types of exceptions separately and provide specific logic for each exception type. The <span class="spanHT">catch</span> blocks are evaluated in the order they appear, so the most specific exceptions should be caught first, followed by more general exceptions.</p>



<button class="shbtn" id="shbtn85086" onclick="showHideBlock(85086)">&#9660; <u>Show example</u></button>
<div id="shdiv85086" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">try</span>
        {
            int[] numbers = { 1, 2, 3 };

            <span class="com">// This will throw an IndexOutOfRangeException</span>
            Console.WriteLine(numbers[3]);

            <span class="key">int</span> a = 10;
            <span class="key">int</span> b = 0;

            <span class="com">// This will throw a DivideByZeroException</span>
            Console.WriteLine(a / b);
        }
        <span class="key" style="background:#f2f19d;">catch</span> (IndexOutOfRangeException ex)
        {
            Console.WriteLine(<span class="str">"Index out of range: "</span> + ex.Message);
        }
        <span class="key" style="background:#f2f19d;">catch</span> (DivideByZeroException ex)
        {
            Console.WriteLine(<span class="str">"Cannot divide by zero: "</span> + ex.Message);
        }
        <span class="key" style="background:#f2f19d;">catch</span> (Exception ex)
        {
            Console.WriteLine(<span class="str">"An error occurred: "</span> + ex.Message);
        }
        <span class="key">finally</span>
        {
            Console.WriteLine(<span class="str">"This will always execute."</span>);
        }
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between &#8216;throw&#8217; and &#8216;throw ex&#8217; in C#?</strong></h3>



<p class="custp1 p-mb-0">The difference between <span class="spanHT">throw</span> and <span class="spanHT">throw ex</span> in C# lies in how they affect the exception&#8217;s stack trace when rethrowing an exception. </p>



<p class="custp1 p-mb-0"><strong>throw &#8211;</strong> <strong><em>Preserves Stack Trace:</em></strong> Using <span class="spanHT">throw</span> inside a <span class="spanHT">catch</span> block rethrows the current exception while preserving the original stack trace. This is useful for debugging, as it allows you to see the original point where the exception was thrown.</p>



<p class="custp1 p-mb-0"><strong>throw ex &#8211; </strong><em><strong>Resets Stack Trace</strong>:</em> Using <span class="spanHT">throw ex</span> resets the stack trace to the current location in the <span class="spanHT">catch</span> block. This means the stack trace will start from the point where the exception is rethrown, losing the original context.</p>



<button class="shbtn" id="shbtn93293" onclick="showHideBlock(93293)">&#9660; <u>Show example</u></button>
<div id="shdiv93293" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Using throw:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">try</span>
        {
            CauseException();
        }
        <span class="key">catch</span> (Exception ex)
        {
            Console.WriteLine(<span class="str">"Handling exception and rethrowing..."</span>);
			
            <span class="com">// Rethrows the exception <b>preserving the original stack trace</b></span>
            <span class="key" style="background:#f2f19d;">throw</span>;
        }
    }

    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> CauseException()
    {
        <span class="key" style="background:#f2f19d;">throw new</span> InvalidOperationException(<span class="str">"An error occurred."</span>);
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Using throw ex:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">try</span>
        {
            CauseException();
        }
        <span class="key">catch</span> (Exception ex)
        {
            Console.WriteLine(<span class="str">"Handling exception and rethrowing..."</span>);
			
            <span class="com">// Rethrows the exception but <b>resets the stack trace</b></span>
            <span style="background:#f2f19d;"><span class="key">throw</span> ex;</span>
        }
    }

    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> CauseException()
    {
        <span class="key" style="background:#f2f19d;">throw new</span> InvalidOperationException(<span class="str">"An error occurred."</span>);
    }
} </code></pre>



</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you define a custom exception in C#?</strong></h3>



<p class="custp1 p-mb-0">A custom exception is a user-defined class that extends the <span class="spanHT">Exception</span> class. It allows you to create specific error types tailored to your application&#8217;s needs. Custom exceptions can include custom properties, methods, and constructors for more detailed error handling and messaging.</p>



<button class="shbtn" id="shbtn44272" onclick="showHideBlock(44272)">&#9660; <u>Show example</u></button>
<div id="shdiv44272" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span style="background:#f2f19d;">CustomInvalidAgeException : <span class="custkey"><b>Exception</b></span></span>
{
    <span class="com">// Default constructor</span>
    <span class="key">public</span> CustomInvalidAgeException()
    {
    }

    <span class="com">// Constructor that takes a message</span>
    <span class="key">public</span> CustomInvalidAgeException(<span class="key">string</span> message)
        : <span class="key">base</span>(message)
    {
    }

    <span class="com">// Constructor that takes a message and an inner exception</span>
    <span class="key">public</span> CustomInvalidAgeException(<span class="key">string</span> message, Exception inner)
        : <span class="key">base</span>(message, inner)
    {
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">try</span>
        {
            ValidateAge(-1);
        }
        <span class="key">catch</span> (<span style="background:#f2f19d;">CustomInvalidAgeException</span> ex)
        {
            Console.WriteLine(<span class="str">"Custom Exception Caught: "</span> + ex.Message);
        }
    }

    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> ValidateAge(<span class="key">int</span> age)
    {
        <span class="key">if</span> (age &lt; 0)
        {
            <span class="key">throw new</span> <span style="background:#f2f19d;">CustomInvalidAgeException</span>(<span class="str">"Age cannot be negative."</span>);
        }
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between ref and out parameters in C#?</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th>ref</th>
            <th>out</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Must be initialized before being passed.</td>
            <td>Must be assigned in the called method before returning.</td>
        </tr>
        <tr>
            <td>Can be used to read and modify the value.</td>
            <td>Used to output data from a method, not for input.</td>
        </tr>
        <tr>
            <td>Allows passing a value to a method and modifying it within the method.</td>
            <td>Allows returning multiple values from a method.</td>
        </tr>
        <tr>
            <td><span class="spanHT">ref</span> keyword example below</td>
            <td><span class="spanHT">out</span> keyword example below</td>
        </tr>
    </tbody>
</table>



<button class="shbtn" id="shbtn16215" onclick="showHideBlock(16215)">&#9660; <u>Show example</u></button>
<div id="shdiv16215" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>ref Keyword Example:</b></div>
<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">int</span> number = 10;
        Console.WriteLine(<span class="str">"Before method call: "</span> + number);
        ModifyRef(<span class="key" style="background:#f2f19d;">ref</span> number);
        Console.WriteLine(<span class="str">"After method call: "</span> + number);
    }

    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> ModifyRef(<span class="key" style="background:#f2f19d;">ref</span> <span class="key">int</span> num)
    {
        num = 20; <span class="com">// Modifying the value</span>
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>out Keyword Example:</b></div>
<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">int</span> number;
        InitializeOut(<span class="key" style="background:#f2f19d;">out</span> number);
        Console.WriteLine(<span class="str">"After method call: "</span> + number);
    }

    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> InitializeOut(<span class="key" style="background:#f2f19d;">out</span> <span class="key">int</span> num)
    {
        num = 30; <span class="com">// Assigning a value</span>
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between &#8216;in&#8217; and &#8216;out&#8217; parameters?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">in</span> and <span class="spanHT">out</span> keywords in C# are used to define how parameters are passed to methods. Both are special types of parameters, but they serve different purposes.</p>



<br>
<table>
    <thead>
        <tr>
            <th>&#39;in&#39; Parameter</th>
            <th>&#39;out&#39; Parameter</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Used to pass arguments by reference, ensuring the method does not modify the argument&#39;s value.</td>
            <td>Used to pass arguments by reference, allowing the method to modify and return the value.</td>
        </tr>
        <tr>
            <td>The argument must be initialized before being passed to the method.</td>
            <td>The argument does not need to be initialized before being passed; it must be assigned a value within the method.</td>
        </tr>
        <tr>
            <td>The method cannot modify the value of the in parameter.</td>
            <td>The method must assign a value to the out parameter before it returns.</td>
        </tr>
        <tr>
            <td>Use when you want to pass a large object by reference to avoid copying but still prevent modifications.</td>
            <td>Use when you need to return multiple values from a method or ensure a value is assigned inside the method.</td>
        </tr>
        <tr>
            <td>Immutable within the method.</td>
            <td>Mutable within the method.</td>
        </tr>
    </tbody>
</table>



<button class="shbtn" id="shbtn3917" onclick="showHideBlock(3917)">&#9660; <u>Show example</u></button>
<div id="shdiv3917" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>&#39;in&#39; Parameter Example</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ProcessData(<span class="key" style="background:#f2f19d;">in</span> <span class="key">int</span> value)
{
    value = value + 1; <span style="color:red;">// This will cause a compile-time error.</span>
    Console.WriteLine(value);
}

<span class="key">int</span> number = 10;
ProcessData(<span class="key">in</span> number);  <span class="com">// Passes the number by reference, but it cannot be modified inside the method.</span>
</code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>&#39;out&#39; Parameter Example</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> GetData(<span class="key" style="background:#f2f19d;">out</span> <span class="key">int</span> value)
{
    value = 42;  <span class="com">// Must assign a value before the method returns.</span>
}

<span class="key">int</span> number;
GetData(<span class="key">out</span> number);  <span class="com">// Passes the number by reference, and the method assigns a value to it.</span>
Console.WriteLine(number);  <span class="com">// Output: 42</span>
</code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the &#8216;params&#8217; keyword?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">params</span> keyword allows you to specify a method parameter that takes a variable number of arguments. It is used to specify a parameter that takes an array of arguments, making it possible to pass a variable number of arguments without explicitly creating an array. It </p>



<button class="shbtn" id="shbtn20337" onclick="showHideBlock(20337)">&#9660; <u>Show example</u></button>
<div id="shdiv20337" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        PrintNumbers(1, 2, 3, 4, 5); <span class="com">// Passing multiple arguments</span>
        PrintNumbers(10, 20);        <span class="com">// Passing fewer arguments</span>
        PrintNumbers();              <span class="com">// No arguments</span>
    }

    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> PrintNumbers(<span class="key" style="background:#f2f19d;">params</span> int[] numbers)
    {
        <span class="key">foreach</span> (<span class="key">int</span> number <span class="key">in</span> numbers)
        {
            Console.WriteLine(number);
        }
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you define and use Indexers in C#?</strong></h3>



<p class="custp1 p-mb-0">Indexers allow instances of a &#8216;class&#8217; or &#8216;struct&#8217; to be indexed just like arrays. They are defined using the <span class="spanHT">this</span> keyword followed by a parameter list inside square brackets. Indexers provide a way to access class or struct data in a similar way to accessing elements in an array.</p>



<button class="shbtn" id="shbtn27930" onclick="showHideBlock(27930)">&#9660; <u>Show example</u></button>
<div id="shdiv27930" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Define an Indexer:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> SampleCollection&lt;T&gt
{
    <span class="key">private</span> T[] array = <span class="key">new</span> T[100];

    <span class="key">public</span> T <span class="key"  style="background:#f2f19d;">this</span>[int index]
    {
        <span class="key">get</span> { <span class="key">return</span> array[index]; }
        <span class="key">set</span> { array[index] = value; }
    }
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Use the Indexer:</b></div>
<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">var</span> collection = <span style="background:#f2f19d;"><span class="key">new</span> SampleCollection&lt;<span class="key">string</span>&gt();</span>
        collection[0] = <span class="str">"Hello"</span>;
        collection[1] = <span class="str">"World"</span>;

        Console.WriteLine(collection[0]); <span class="com">// Output: Hello</span>
        Console.WriteLine(collection[1]); <span class="com">// Output: World</span>
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement Generic Classes and Methods in C#?</strong></h3>



<p class="custp1 p-mb-0">Generics allow you to define classes, methods, and other data structures without specifying the exact data type. This enables code reusability and type safety.</p>



<button class="shbtn" id="shbtn36736" onclick="showHideBlock(36736)">&#9660; <u>Show example</u></button>
<div id="shdiv36736" style="display: none;">

<pre class="pchl"><code><span class="com"><b>// Implementing a Generic Class</b></span>
<span class="key">public</span> <span class="key">class</span> GenericClass<span style="background:#f2f19d;">&lt;T&gt</span>
{
    <span class="key">private</span> <span style="background:#f2f19d;">T</span> data;

    <span class="key">public</span> <span style="background:#f2f19d;">T</span> Data
    {
        <span class="key">get</span> { <span class="key">return</span> data; }
        <span class="key">set</span> { data = value; }
    }

    <span class="key">public</span> <span class="key">void</span> DisplayData()
    {
        Console.WriteLine(<span class="str">"Data: "</span> + data);
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="com"><b>// Implementing a Generic Method</b></span>
    <span class="key">public</span> <span class="key">void</span> PrintData<span style="background:#f2f19d;">&lt;T&gt</span>(<span style="background:#f2f19d;">T</span> data)
    {
        Console.WriteLine(<span class="str">"Data: "</span> + data);
    }

    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Using Generic Class</span>
        <span class="key">var</span> intInstance = <span style="background:#f2f19d;"><span class="key">new</span> GenericClass&lt;<span class="key">int</span>&gt();</span>
        intInstance.Data = 10;
        intInstance.DisplayData(); <span class="com">// Output: Data: 10</span>

        <span class="key">var</span> stringInstance = <span style="background:#f2f19d;"><span class="key">new</span> GenericClass&lt;<span class="key">string</span>&gt();</span>
        stringInstance.Data = <span class="str">"Hello"</span>;
        stringInstance.DisplayData(); <span class="com">// Output: Data: Hello</span>

        <span class="com">// Using Generic Method</span>
        <span class="key">var</span> program = <span class="key">new</span> Program();
        program.<span style="background:#f2f19d;">PrintData(123)</span>;      <span class="com">// Output: Data: 123</span>
        program.<span style="background:#f2f19d;">PrintData(<span class="str">"Hello"</span>)</span>;  <span class="com">// Output: Data: Hello</span>
        program.<span style="background:#f2f19d;">PrintData(45.67)</span>;    <span class="com">// Output: Data: 45.67</span>
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of constraints in generic programming?</strong></h3>



<p class="custp1 p-mb-0">Constraints in generic programming allow developers to write more robust and versatile generic code by specifying the necessary conditions that type arguments must fulfill. It are used to enforce specific requirements on type parameters, ensuring type safety, enabling access to members, providing flexibility, and enhancing code clarity. </p>



<p class="custp1 p-mb-0"><strong><em>Types of Constraints:</em></strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>where T : struct</strong>: The type argument must be a value type.</li>



<li><strong>where T : class</strong>: The type argument must be a reference type.</li>



<li><strong>where T : new()</strong>: The type argument must have a parameterless constructor.</li>



<li><strong>where T : &lt;base class name&gt;</strong>: The type argument must be or derive from the specified base class.</li>



<li><strong>where T : &lt;interface name&gt;</strong>: The type argument must implement the specified interface.</li>



<li><strong>where T : U</strong>: The type argument must be or derive from the type argument U.</li>
</ol>



<button class="shbtn" id="shbtn29072" onclick="showHideBlock(29072)">&#9660; <u>Show example</u></button>
<div id="shdiv29072" style="display: none;" class="shdt">

<pre class="pchl"><code><span class="com">// Define a generic class with constraints</span>
<span class="key">public</span> <span class="key">class</span> GenericClass&lt;T&gt <span style="background:#f2f19d;"><span class="key">where</span> T : <span class="custkey">IComparable</span>, <span class="key">new</span>()</span>
{
    <span class="key">private</span> T data;

    <span class="key">public</span> T Data
    {
        <span class="key">get</span> { <span class="key">return</span> data; }
        <span class="key">set</span> { data = value; }
    }

    <span class="com">// Method to compare the data with another instance of the same type</span>
    <span class="key">public</span> <span class="key">int</span> Compare(T other)
    {
        <span class="key">return</span> data.CompareTo(other);
    }

    <span class="com">// Constructor</span>
    <span class="key">public</span> GenericClass()
    {
        <span class="com">// Instantiate using the parameterless constructor constraint</span>
        data = <span class="key"><b>new</b></span> <b>T()</b>;
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="key">var</span> instance = <span class="key">new</span> GenericClass&lt;<span class="key">int</span>&gt();
        instance.Data = 10;

        Console.WriteLine(instance.Compare(20)); <span class="com">// Output: -1 (since 10 < 20)</span>
    }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;"><b>Constraints Used:</b><br>
1) <b>where T : IComparable</b>: Ensures that the type argument implements the IComparable interface.<br>
2) <b>where T : new()</b>: Ensures that the type argument has a parameterless constructor.
</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are anonymous types in C#?</strong></h3>



<p class="custp1 p-mb-0">Anonymous types provide a way to create simple, immutable object types without having to explicitly define a class. They are useful for encapsulating a set of read-only properties into a single object for convenience, typically when you want to return multiple values from a method or perform quick data processing operations without the overhead of defining a new class. Typically used within the scope they are defined, such as within a method. Anonymous types are created using the <span class="spanHT">new</span> keyword followed by an object initializer syntax. </p>



<p class="custp1 p-mb-0"><strong><em>syntax:</em></strong></p>



<pre class="pchl"><code><span class="key">var</span> anonymousObject = <span class="key" style="background:#f2f19d;">new</span> { Property1 = <span class="str">"Hello"</span>, Property2 = 123 }; </code></pre><br>



<button class="shbtn" id="shbtn34441" onclick="showHideBlock(34441)">&#9660; <u>Show example</u></button>
<div id="shdiv34441" style="display: none;">

<br>
<div style="padding-left: 0.3125rem;"><b>Example 1:</b></div>
<pre class="pchl"><code><span class="key">var</span> person = <span class="key" style="background:#f2f19d;">new</span> { Name = <span class="str">"John Doe"</span>, Age = 30, Occupation = <span class="str">"Developer"</span> }; </code></pre>


<br>
<div style="padding-left: 0.3125rem;"><b>Example 2:</b></div>
<pre class="pchl"><code><span class="key">var</span> people = <span class="key" style="background:#f2f19d;">new</span>[]
{
	<span class="key">new</span> { Name = <span class="str">"John Doe"</span>, Age = 30 },
	<span class="key">new</span> { Name = <span class="str">"Jane Smith"</span>, Age = 25 },
	<span class="key">new</span> { Name = <span class="str">"Sam Brown"</span>, Age = 35 }
}; </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the var keyword?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">var</span> keyword is used for implicitly typing local variables. It allows the compiler to infer the type of the variable from the right-hand side of the assignment at compile-time. The <span class="spanHT">var</span> keyword enhances code readability and reduces redundancy without sacrificing type safety.</p>



<p class="custp1 p-mb-0"><strong><em>example:</em></strong></p>



<pre class="pchl"><code><span class="key">var</span> number = 10; <span class="com">// The type of <b>number</b> is inferred as int</span></code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use the dynamic keyword?</strong></h3>



<p class="custp1 p-mb-0">The dynamic keyword in C# provides a powerful mechanism for deferring type resolution until runtime, making it ideal for interacting with dynamic languages, COM objects, and scenarios where type information is not available at compile-time. While it offers significant flexibility, it should be used judiciously due to the performance overhead and potential for runtime errors. </p>



<p class="custp1 p-mb-0">Unlike <span class="spanHT">var</span>, which requires the type to be known at compile-time, <span class="spanHT">dynamic</span> variables are checked at runtime. </p>



<br>



<p class="p-mb-0"><strong>COM Interop Example:</strong></p>



<pre class="pchl"><code><span class="com">// COM Interop Example</span>
<span class="key">dynamic</span> excelApp = Activator.CreateInstance(Type.GetTypeFromProgID(<span class="str">"Excel.Application"</span>));
excelApp.Visible = true;
excelApp.Workbooks.Add();
excelApp.Cells[1, 1].Value = <span class="str">"Hello, Excel!"</span>; </code></pre>
<br>



<p class="p-mb-0"><strong>Disadvantages &#8211;</strong> Performance Overhead, Lack of IntelliSense, Potential for Runtime Errors.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is &#8216;thread&#8217; in C#?</strong></h3>



<p class="custp1 p-mb-0">A thread in C# is a basic unit of execution within a process, allowing concurrent operations. Each process can have multiple threads, which share the process&#8217;s resources but execute independently. Threads allow a program to perform multiple operations concurrently, making efficient use of CPU resources and improving application performance, especially for tasks that involve waiting or are computationally intensive. Creating a thread can be done using the <span class="spanHT">Thread</span> class in the <span class="spanHT">System.Threading</span> namespace. Provides Thread Safety, ensuring that multiple threads do not interfere with each other when accessing shared resources. </p>



<p class="custp1 p-mb-0"><strong>Multithreading</strong>: The ability to run multiple threads concurrently within the same process. It helps in performing complex or multiple tasks at the same time. </p>



<p class="custp1 p-mb-0"><strong>Thread Life Cycle</strong>:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Unstarted</strong>: The thread is created but not yet started.</li>



<li><strong>Running</strong>: The thread is executing.</li>



<li><strong>Blocked/Waiting</strong>: The thread is blocked or waiting for a resource or event.</li>



<li><strong>Dead</strong>: The thread has finished execution or has been terminated.</li>
</ul>



<button class="shbtn" id="shbtn11542" onclick="showHideBlock(11542)">&#9660; <u>Show example</u></button>
<div id="shdiv11542" style="display: none;">

<pre class="pchl"><code><span class="key">using</span> System;
<span style="background:#f2f19d;"><span class="key">using</span> System.Threading;</span>

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Define a method that will run on the new thread</span>
        <span class="key">void</span> ThreadMethod()
        {
            <span class="key">for</span> (<span class="key">int</span> i = 0; i &lt; 5; i++)
            {
                Console.WriteLine($<span class="str">"Thread Method: {i}"</span>);
                Thread.Sleep(1000); <span class="com">// Simulate some work</span>
            }
        }

        <span class="com">// Create a thread, passing the method as a ThreadStart delegate</span>
        <span style="background:#f2f19d;">Thread</span> thread = <span class="key">new</span> <span style="background:#f2f19d;">Thread</span>(<span class="key">new</span> <span style="background:#f2f19d;">ThreadStart</span>(ThreadMethod));

        <span class="com">// Start the thread</span>
        <span style="background:#f2f19d;">thread.Start();</span>

        <span class="com">// Continue with the main thread</span>
        <span class="key">for</span> (<span class="key">int</span> i = 0; i &lt; 5; i++)
        {
            Console.WriteLine($<span class="str">"Main Method: {i}"</span>);
            <span style="background:#f2f19d;">Thread.Sleep(500);</span>
        }

        <span class="com">// Wait for the thread to complete</span>
        <span style="background:#f2f19d;">thread.Join();</span>
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is asynchronous programming? (or) How do you use Task, async, await keywords in C#</strong>.</h3>



<p class="custp1 p-mb-0">In C#, the <span class="spanHT">Task</span>, <span class="spanHT">async</span>, and <span class="spanHT">await</span> keywords are used for asynchronous programming. This approach is called &#8220;asynchronous programming&#8221; or &#8220;async/await programming.&#8221; It allows you to write code that performs tasks asynchronously, meaning the tasks run independently of the main application flow, without blocking it. This is especially useful for I/O-bound operations like file access, network calls, or database queries, as well as for CPU-bound operations that might take a long time to complete.</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Task</strong>: Represents an asynchronous operation. It&#8217;s part of the Task Parallel Library (TPL) in the <span class="spanHT">System.Threading.Tasks</span> namespace.</li>



<li><strong>async</strong>: Indicates that a method is asynchronous and can contain <span class="spanHT">await</span> expressions.</li>



<li><strong>await</strong>: Pauses the execution of the async method until the awaited task completes.</li>
</ul>



<button class="shbtn" id="shbtn54656" onclick="showHideBlock(54656)">&#9660; <u>Show example</u></button>
<div id="shdiv54656" style="display: none;">

<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Net.Http;
<span style="background:#f2f19d;"><span class="key">using</span> System.Threading.Tasks;</span>

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span style="background:#f2f19d;"><span class="key">async</span> <span class="custkey">Task</span></span> Main(string[] args)
    {
        Console.WriteLine(<span class="str">"Starting..."</span>);

        <span class="com">// Call the asynchronous method</span>
        <span class="key">string</span> result = <span class="key" style="background:#f2f19d;">await</span> FetchDataAsync();

        Console.WriteLine($<span class="str">"Result: {result}"</span>);
        Console.WriteLine(<span class="str">"Finished."</span>);
    }

    <span class="key">public</span> <span class="key">static</span> <span style="background:#f2f19d;"><span class="key">async</span> <span class="custkey">Task</span>&lt;<span class="key">string</span>&gt</span> FetchDataAsync()
    {
        <span class="key">using</span> (HttpClient client = <span class="key">new</span> HttpClient())
        {
            <span class="com">// Asynchronously fetch data from a URL</span>
            HttpResponseMessage response = <span class="key" style="background:#f2f19d;">await</span> client.GetAsync(<span class="str">"https://api.github.com"</span>);
            
            <span class="com">// Ensure the response was successful</span>
            response.EnsureSuccessStatusCode();
            
            <span class="com">// Asynchronously read the response content as a string</span>
            <span class="key">string</span> responseBody = <span class="key" style="background:#f2f19d;">await</span> response.Content.ReadAsStringAsync();
            
            <span class="key">return</span> responseBody;
        }
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the &#8216;lock&#8217; statement in C#?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">lock</span> statement ensures that a block of code runs to completion by only one thread at a time. This prevents multiple threads from accessing a shared resource simultaneously (<em>Thread Safety</em>), which can lead to race conditions and data corruption. The <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock" target="_blank" rel="noopener"><span class="cLink3">lock</span></a> statement provides a mechanism for enforcing <em>thread synchronization</em>, ensuring that only one thread can enter the critical section of code at any given moment. Helps <em>avoid deadlocks</em> by locking on a private object instead of <span class="spanHT">this</span> or a type.</p>



<button class="shbtn" id="shbtn50239" onclick="showHideBlock(50239)">&#9660; <u>Show example</u></button>
<div id="shdiv50239" style="display: none;" class="shdt">

<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Threading;

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">private</span> <span class="key">static</span> <span class="key">readonly</span> <span class="key">object</span> lockObject = <span class="key">new</span> <span class="key">object</span>();
    <span class="key">private</span> <span class="key">static</span> <span class="key">int</span> sharedResource = 0;

    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        Thread thread1 = <span class="key">new</span> Thread(IncrementResource);
        Thread thread2 = <span class="key">new</span> Thread(IncrementResource);

        thread1.Start();
        thread2.Start();

        thread1.Join();
        thread2.Join();

        Console.WriteLine($<span class="str">"Final value of sharedResource: {sharedResource}"</span>);
    }

    <span class="key">private</span> <span class="key">static</span> <span class="key">void</span> IncrementResource()
    {
        <span class="key">for</span> (<span class="key">int</span> i = 0; i &lt; 1000; i++)
        {
            <span class="key" style="background:#f2f19d;">lock</span> (lockObject)
            {
                sharedResource++;
            }
        }
    }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem;">
<div><b>Explanation:</b></div>
<ol class="ol1 ol-mb-0">
<li><strong>Shared Resource</strong>: <strong>&#8216;sharedResource&#8217;</strong> is a variable that both threads will try to increment.</li>

<li><strong>Lock Object</strong>: <strong>&#8216;lockObject&#8217;</strong> is a private object used to synchronize access to the critical section.</li>

<li><strong>Critical Section</strong>: The code inside the <span class="spanHT">lock</span> statement (<strong>sharedResource++</strong>) is the critical section that should not be accessed by multiple threads simultaneously.</li>
</ol>
</div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Guidelines for using &#8216;lock&#8217;</strong></h3>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Use a private object</strong>: Always use a private object for locking. Never lock on publicly accessible objects, instances of <span class="spanHT">this</span>, or types, as this can lead to unexpected behavior and deadlocks.</li>



<li><strong>Keep the critical section small</strong>: Minimize the code inside the <span class="spanHT">lock</span> statement to reduce the chance of contention and improve performance.</li>



<li><strong>Avoid locking on strings</strong>: Strings are immutable and interned by the CLR, which means that locking on a string can inadvertently lock on the same string instance across different parts of the code.</li>
</ul>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the &#8216;is&#8217; and &#8216;as&#8217; operators?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">is</span> and <span class="spanHT">as</span> operators in C# are used for type checking and type casting, respectively. They are useful for working with objects when you need to verify or convert their types at runtime. </p>



<br>



<p class="p-mb-0"><strong>&#8216;is&#8217; Operator:</strong> The <span class="spanHT">is</span> operator checks if an object is compatible with a given type. It returns <strong>true</strong> if the object can be cast to the specified type without throwing an exception; otherwise, it returns <strong>false</strong>. </p>



<pre class="pchl"><code><span class="key">if</span> (obj <span class="key" style="background:#f2f19d;">is</span> <span class="key">string</span>) { } </code></pre><br>



<p class="custp1 p-mb-0"><strong>&#8216;as&#8217; Operator:</strong> The <span class="spanHT">as</span> operator attempts to cast an object to a specified type. If the cast is successful, it returns the object as the new type. If the cast fails, it returns <strong>null</strong> instead of throwing an exception.</p>



<pre class="pchl"><code><span class="key">string</span> str = obj <span class="key" style="background:#f2f19d;">as</span> string; </code></pre>



<br><br>
<table>
    <thead>
        <tr>
            <th>is Operator</th>
            <th>as Operator</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Checks if an object is of a certain type</td>
            <td>Casts an object to a specified type</td>
        </tr>
        <tr>
            <td>Returns true or false</td>
            <td>Returns the object as the new type, or null</td>
        </tr>
        <tr>
            <td>Does not throw exceptions</td>
            <td>Does not throw exceptions (returns null on failure)</td>
        </tr>
        <tr>
            <td>Used for type checking</td>
            <td>Used for safe type casting</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use attributes in C#?</strong></h3>



<p class="custp1 p-mb-0">Attributes in C# provide a way to add metadata to your code. They can be applied to various code elements, such as classes, methods, properties, fields, and more. Attributes are used to store declarative information and can be accessed at runtime using reflection.</p>



<button class="shbtn" id="shbtn85337" onclick="showHideBlock(85337)">&#9660; <u>Show example</u></button>
<div id="shdiv85337" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;">

<div><b>Common Built-in Attributes</b></div>
<div class="custp1"><b>a) [Serializable]:</b> Indicates that a class can be serialized.</div>
<div>
<pre class="pchl"><code>[<span style="background:#f2f19d;">Serializable</span>]
<span class="key">public</span> <span class="key">class</span> SerializableClass
{
    <span class="com">// Class implementation</span>
} </code></pre>
</div>

<br>
<div class="custp1"><b>b) [Obsolete]:</b> Marks a program element as obsolete, optionally providing a message and an error flag.</div>
<div>
<pre class="pchl"><code>[<span style="background:#f2f19d;">Obsolete</span>(<span class="str">"This method is obsolete. Use NewMethod instead."</span>, <span class="key">true</span>)]
<span class="key">public</span> <span class="key">void</span> OldMethod()
{
    <span class="com">// Method implementation</span>
} </code></pre>
</div>

<br>
<div class="custp1"><b>c) [DllImport]:</b> Used to import a method from an unmanaged DLL.</div>
<div>
<pre class="pchl"><code>[<span style="background:#f2f19d;">DllImport</span>(<span class="str">"user32.dll"</span>)]
<span class="key">public</span> <span class="key">static</span> <span class="key">extern</span> <span class="key">int</span> MessageBox(IntPtr hWnd, <span class="key">string</span> text, <span class="key">string</span> caption, <span class="key">uint</span> type); </code></pre>
</div>

<br>
<div class="custp1"><b>d) [Conditional]:</b> Specifies that a method call or attribute should be included or omitted based on the presence of a specified preprocessor symbol.</div>
<div>
<pre class="pchl"><code>[<span style="background:#f2f19d;">Conditional</span>(<span class="str">"DEBUG"</span>)]
<span class="key">public</span> <span class="key">void</span> DebugOnlyMethod()
{
    <span class="com">// Method implementation</span>
} </code></pre>
</div>


</div>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the &#8216;AttributeUsage&#8217; attribute?</strong></h3>



<p class="custp1 p-mb-0">The AttributeUsage attribute is used to specify the kinds of program elements to which a <strong><em>custom attribute</em></strong> can be applied. It allows you to control where and how your custom attribute can be used, and to define additional settings such as whether the attribute can be applied multiple times or inherited by derived classes. </p>



<p class="custp1 p-mb-0"><strong>Key Properties of &#8216;AttributeUsage&#8217;:</strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>ValidOn</strong>: Specifies the program elements (such as classes, methods, properties, etc.) to which the attribute can be applied using the <span class="spanHT">AttributeTargets</span> enum. <br><strong><em>example values:</em></strong> <span class="spanHT">AttributeTargets.Class</span>, <span class="spanHT">AttributeTargets.Method</span>, <span class="spanHT">AttributeTargets.Property</span>, etc.</li>



<li class="custp1"><strong>AllowMultiple</strong>: If <span class="spanHT">true</span>, the attribute can be applied more than once to the same element. The default value is <span class="spanHT">false</span>.</li>



<li class="custp1"><strong>Inherited</strong>: If <span class="spanHT">true</span>, the attribute can be inherited by derived classes or overriding members. The default value is <span class="spanHT">false</span>.</li>
</ol>



<button class="shbtn" id="shbtn54165" onclick="showHideBlock(54165)">&#9660; <u>Show example</u></button>
<div id="shdiv54165" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Custom Attribute &#8211; Example</b></div>

<pre class="pchl"><code><span class="key">using</span> System;

<span style="background:#f2f19d;">[<b>AttributeUsage</b>(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = <span class="key">true</span>, Inherited = <span class="key">true</span>)]</span>
<span class="key">public</span> <span class="key">class</span> MyCustomAttribute <span style="background:#f2f19d;">: Attribute</span>
{
    <span class="key">public</span> <span class="key">string</span> Description { get; }

    <span class="key">public</span> MyCustomAttribute(<span class="key">string</span> description)
    {
        Description = description;
    }
}

[<span style="background:#f2f19d;">MyCustomAttribute</span>(<span class="str">"This is a custom attribute for the SampleClass."</span>)]
<span class="key">public</span> <span class="key">class</span> SampleClass
{
    [<span style="background:#f2f19d;">MyCustomAttribute</span>(<span class="str">"This is a custom attribute for the SampleMethod."</span>)]
    <span class="key">public</span> <span class="key">void</span> SampleMethod()
    {
        Console.WriteLine(<span class="str">"SampleMethod executed."</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> DerivedClass : SampleClass
{
    <span class="com">// Inherits attributes from SampleClass if Inherited = true</span>
    <span class="key">public</span> <span class="key">override</span> <span class="key">void</span> SampleMethod()
    {
        Console.WriteLine(<span class="str">"Overridden SampleMethod in DerivedClass executed."</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        Type type = <span class="key">typeof</span>(SampleClass);
        object[] classAttributes = type.GetCustomAttributes(<span style="background:#f2f19d;"><span class="key">typeof</span>(MyCustomAttribute)</span>, <span class="key">false</span>);

        <span class="key">foreach</span> (MyCustomAttribute attr <span class="key">in</span> classAttributes)
        {
            Console.WriteLine($<span class="str">"Class Attribute Description: {attr.Description}"</span>);
        }

        MethodInfo method = type.GetMethod(<span class="str">"SampleMethod"</span>);
        object[] methodAttributes = method.GetCustomAttributes(<span style="background:#f2f19d;"><span class="key">typeof</span>(MyCustomAttribute)</span>, <span class="key">false</span>);

        <span class="key">foreach</span> (MyCustomAttribute attr <span class="key">in</span> methodAttributes)
        {
            Console.WriteLine($<span class="str">"Method Attribute Description: {attr.Description}"</span>);
        }
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between Shallow copy and Deep copy in C#?</strong></h3>



<p class="custp1 p-mb-0"><strong>Shallow Copy:</strong> Creates a new object but references the same objects as the original. In other words, it creates a new instance of the original object, but the fields of the new object still reference the same objects as the fields of the original object. Copies the top-level structure of the object. </p>



<p class="custp1 p-mb-0"><strong>Deep Copy:</strong> Creates a new object and recursively copies all objects it references. In other words, it creates a completely independent copy of the original object and all objects that the original object references. Copies the entire object graph.</p>



<button class="shbtn" id="shbtn4685" onclick="showHideBlock(4685)">&#9660; <u>Show example</u></button>
<div id="shdiv4685" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> <span class="custkey">Person</span>
{
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> Address Address { get; set; }

    <span class="key">public</span> <span class="custkey">Person</span> <span style="background:#f2f19d;">ShallowCopy()</span>
    {
        <span class="key">return</span> (<span class="custkey">Person</span>)this.MemberwiseClone();
    }
	
    <span class="key">public</span> <span class="custkey">Person</span> <span style="background:#f2f19d;">DeepCopy()</span>
    {
        <span class="custkey">Person</span> copy = (<span class="custkey">Person</span>)this.MemberwiseClone();
        copy.Address = <span class="key">new</span> Address { City = this.Address.City };
        <span class="key">return</span> copy;
    }
}

<span class="key">public</span> <span class="key">class</span> Address
{
    <span class="key">public</span> <span class="key">string</span> City { get; set; }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="custkey">Person</span> original = <span class="key">new</span> Person
        {
            Name = <span class="str">"John"</span>,
            Address = <span class="key">new</span> Address { City = <span class="str">"New York"</span> }
        };

        <span class="custkey">Person</span> shallowCopy = <span style="background:#f2f19d;">original.ShallowCopy();</span>

        <span class="com">// Both original and copy point to the same Address object</span>
        Console.WriteLine(ReferenceEquals(original.Address, shallowCopy.Address)); <span class="com">// True</span>
		
		
        <span class="custkey">Person</span> deepCopy = <span style="background:#f2f19d;">original.DeepCopy();</span>

        <span class="com">// original and copy point to different Address objects</span>
        Console.WriteLine(ReferenceEquals(original.Address, deepCopy.Address)); <span class="com">// False</span>
    }
} </code></pre>

</div>



<br><br>
<table>
    <thead>
        <tr>
            <th>Shallow Copy</th>
            <th>Deep Copy</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Copies only the top-level structure</td>
            <td>Copies the entire object graph</td>
        </tr>
        <tr>
            <td>References the same instances</td>
            <td>Creates new instances of referenced objects</td>
        </tr>
        <tr>
            <td>Used when the object is simple or immutable</td>
            <td>Used when the object is complex and mutable</td>
        </tr>
        <tr>
            <td>Generally faster</td>
            <td>Generally slower due to recursive copying</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement ICloneable interface in C#?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">ICloneable</span> interface in C# is used to create a clone (a copy) of an object. To implement it you need to define the <span class="spanHT">Clone</span> method, which returns a copy of the current instance. you can implement either a <strong>shallow copy</strong> or a <strong>deep copy</strong>.</p>



<button class="shbtn" id="shbtn37111" onclick="showHideBlock(37111)">&#9660; <u>Show example</u></button>
<div id="shdiv37111" style="display: none;">

<br>
<div style="padding-left: 0.3125rem;"><b>ICloneable Example with Shallow Copy:</b></div>
<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">public</span> <span class="key">class</span> <span class="custkey">Person</span> <span style="background:#f2f19d;">: <b>ICloneable</b></span>
{
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> Address Address { get; set; }

    <span style="background:#f2f19d;"><span class="key">public</span> <span class="key">object</span> <b>Clone()</b></span>
    {
        <span class="key">return</span> this.MemberwiseClone();
    }
}

<span class="key">public</span> <span class="key">class</span> Address
{
    <span class="key">public</span> <span class="key">string</span> City { get; set; }
}

<span class="key">public</span> <span class="key">class</span> Program
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="custkey">Person</span> original = <span class="key">new</span> <span class="custkey">Person</span>
        {
            Name = <span class="str">"John"</span>,
            Address = <span class="key">new</span> Address { City = <span class="str">"New York"</span> }
        };

        <span class="custkey">Person</span> copy = <span style="background:#f2f19d;">(<span class="custkey">Person</span>)original.Clone();</span>

        Console.WriteLine($<span class="str">"Original Name: {original.Name}, City: {original.Address.City}"</span>);
        Console.WriteLine($<span class="str">"Copy Name: {copy.Name}, City: {copy.Address.City}"</span>);

        <span class="com">// Modifying the copy's Address</span>
        copy.Address.City = <span class="str">"Los Angeles"</span>;

        <span class="com">// The original's Address is also changed because it's a shallow copy</span>
        Console.WriteLine($<span class="str">"Original City after modification: {original.Address.City}"</span>);
        Console.WriteLine($<span class="str">"Copy City after modification: {copy.Address.City}"</span>);
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are nullable types in C#?</strong></h3>



<p class="custp1 p-mb-0">Nullable types allow value types (such as <span class="spanHT">int</span>, <span class="spanHT">double</span>, <span class="spanHT">bool</span>, etc.) to represent null values. This is useful when you need to represent the absence of a value for value types, which normally cannot be null. </p>



<p class="custp1 p-mb-0">A nullable type is declared using the <span class="spanHT">?</span> syntax or the <span class="spanHT">Nullable&lt;T&gt;</span> generic type. For example, <span class="spanHT">int?</span> and <span class="spanHT">Nullable&lt;int&gt;</span> both represent a nullable integer.</p>



<button class="shbtn" id="shbtn1476" onclick="showHideBlock(1476)">&#9660; <u>Show example</u></button>
<div id="shdiv1476" style="display: none;">

<pre class="pchl"><code><span class="key">int</span><span style="background:#f2f19d;">?</span> nullableInt = <span class="key">null</span>;

<span class="com">// You can check if a nullable type has a value using the <b>HasValue</b> property or by comparing it to null.</span>
<span class="key">if</span> (nullableInt<span style="background:#f2f19d;">.HasValue</span>) 
{
	<span class="com">// If you are sure that the nullable type has a value, you can access it using the <b>Value</b> property.</span>
	<span class="key">int</span> value = nullableInt<span style="background:#f2f19d;">.Value</span>;
}</code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the ?? operator?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">??</span> operator in C# is known as the null-coalescing operator. Its primary purpose is to provide a default value for nullable types or reference types when they are <strong>null</strong>. </p>



<p class="custp1 p-mb-0">The <span class="spanHT">??</span> operator returns the left-hand operand if it is not <strong>null</strong>; otherwise, it returns the right-hand operand.</p>



<button class="shbtn" id="shbtn8113" onclick="showHideBlock(8113)">&#9660; <u>Show example</u></button>
<div id="shdiv8113" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>With Nullable Types:</b></div>
<pre class="pchl"><code><span class="key">int</span>? nullableInt = <span class="key">null</span>;
<span class="key">int</span> result = nullableInt <span style="background:#f2f19d;">??</span> 10;
Console.WriteLine(result); <span class="com">// Output: 10</span></code></pre>


<br>
<div style="padding-left: 0.3125rem;"><b>With Reference Types:</b></div>
<pre class="pchl"><code><span class="key">string</span> str = null;
<span class="key">string</span> result = str <span style="background:#f2f19d;">??</span> <span class="str">"default string"</span>;
Console.WriteLine(result); <span class="com">// Output: default string</span></code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you handle null values with nullable types?</strong></h3>



<br>
<ol class="ol1 ol1-mb-0">
<li><strong>Using &#8216;HasValue&#8217; Property:</strong> The <span class="spanHT">HasValue</span> property indicates whether a nullable type contains a non-null value.
<br> 
<button class="shbtn" style="margin-top:0" id="shbtn18087" onclick="showHideBlock(18087)" fdprocessedid="r756xn">▼ <u>Show example</u></button> 
<div id="shdiv18087" style="display: none;"> <pre class="pchl"><code><span class="key">int</span>? nullableInt = <span class="key">null</span>; 
<span class="key">if</span> (nullableInt<span style="background:#f2f19d;">.HasValue</span>)  { }</code></pre> 
</div> 
</li>

<li class="custp1"><strong>Using &#8216;Value&#8217; Property:</strong> The <span class="spanHT">Value</span> property retrieves the value of the nullable type if &#8216;HasValue&#8217; is &#8216;true&#8217;. Be cautious, as accessing &#8216;Value&#8217; when &#8216;HasValue&#8217; is &#8216;false&#8217; will throw an &#8216;InvalidOperationException&#8217;. 
<br> 
<button class="shbtn" style="margin-top:0" id="shbtn5320" onclick="showHideBlock(5320)">▼ <u>Show example</u></button> 
<div id="shdiv5320" style="display: none;"> <pre class="pchl"><code><span class="key">int</span>? nullableInt = <span class="key">null</span>; 
<span class="key">if</span> (nullableInt.HasValue)  
{ 
	<span class="key">int</span> value = nullableInt<span style="background:#f2f19d;">.Value</span>; 
}</code></pre> </div>
</li>

<li class="custp1"><strong>Using Null-Coalescing Operator (??):</strong> The null-coalescing operator (<span class="spanHT">??</span>) provides a default value if the nullable type is &#8216;null&#8217;.
<br>
<button class="shbtn" style="margin-top:0" id="shbtn99647" onclick="showHideBlock(99647)">&#9660; <u>Show example</u></button>
<div id="shdiv99647" style="display: none;">
<pre class="pchl"><code><span class="key">int</span>? nullableInt = null;
<span class="key">int</span> value = nullableInt <span style="background:#f2f19d;">??</span> 10; <span class="com">// value will be 10 if nullableInt is null</span>
Console.WriteLine(<span class="str">"Value: "</span> + value); <span class="com">// Output: 10</span></code></pre>
</div>
</li>

<li class="custp1"><strong>Using Null-Conditional Operator (?.):</strong> The null-conditional operator (<span class="spanHT">?.</span>) allows you to access members only if the operand is not &#8216;null&#8217;.
<br>
<button class="shbtn" style="margin-top:0" id="shbtn70167" onclick="showHideBlock(70167)">&#9660; <u>Show example</u></button>
<div id="shdiv70167" style="display: none;">
<pre class="pchl"><code><span class="key">int</span>? nullableInt = null;
<span class="key">int</span>? length = nullableInt<span style="background:#f2f19d;">?.</span>ToString()<span style="background:#f2f19d;">?.</span>Length; <span class="com">// length will be null</span>
Console.WriteLine(<span class="str">"Length: "</span> + (length ?? 0)); <span class="com">// Output: 0</span></code></pre>
</div>
</li>

<li class="custp1"><strong>Default Value with &#8216;GetValueOrDefault&#8217;:</strong> The <span class="spanHT">GetValueOrDefault</span> method returns the value if it is not &#8216;null&#8217;; otherwise, it returns the default value for the type.
<br>
<button class="shbtn" style="margin-top:0" id="shbtn18737" onclick="showHideBlock(18737)">&#9660; <u>Show example</u></button>
<div id="shdiv18737" style="display: none;">
<pre class="pchl"><code><span class="key">int</span>? nullableInt = null;
<span class="key">int</span> value = nullableInt.<span style="background:#f2f19d;">GetValueOrDefault()</span>; <span class="com">// value will be 0 (default for int)</span>
Console.WriteLine(<span class="str">"Value: "</span> + value); <span class="com">// Output: 0</span>

<span class="key">int</span> customDefaultValue = nullableInt.<span style="background:#f2f19d;">GetValueOrDefault(10)</span>; <span class="com">// value will be 10</span>
Console.WriteLine(<span class="str">"Value with custom default: "</span> + customDefaultValue); <span class="com">// Output: 10</span></code></pre>
</div>
</li>

<li class="custp1"><strong>Using &#8216;is&#8217; and Pattern Matching:</strong> Pattern matching with <span class="spanHT">is</span> allows checking and accessing the value if it is not &#8216;null&#8217;.
<br>
<button class="shbtn" style="margin-top:0" id="shbtn71760" onclick="showHideBlock(71760)">&#9660; <u>Show example</u></button>
<div id="shdiv71760" style="display: none;">
<pre class="pchl"><code><span class="key">int</span>? nullableInt = 5;

<span class="key">if</span> (nullableInt <span class="key" style="background:#f2f19d;">is</span> <span class="key">int</span> value)
{
    Console.WriteLine(<span class="str">"Value: "</span> + value); <span class="com">// Output: 5</span>
}
<span class="key">else</span>
{
    Console.WriteLine(<span class="str">"Value is null"</span>);
} </code></pre>
</div>
</li>

</ol>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between the == and Equals methods?</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th></th>
            <th>== Operator</th>
            <th>Equals Method</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Type</th>
            <td>Operator</td>
            <td>Method</td>
        </tr>
        <tr>
            <th>Purpose</th>
            <td>Compares references for reference types, and values for value types</td>
            <td>Compares values or contents of objects</td>
        </tr>
        <tr>
            <th>Overridable</th>
            <td>Yes, can be overloaded in user-defined types</td>
            <td>Yes, can be overridden in user-defined types</td>
        </tr>
        <tr>
            <th>Default Behavior</th>
            <td>Reference comparison for reference types, value comparison for value types</td>
            <td>Reference comparison (default for reference types)</td>
        </tr>
        <tr>
            <th>Null Handling</th>
            <td>Can be used to compare null values</td>
            <td>Can be used to compare null values</td>
        </tr>
        <tr>
            <th>Static/Dynamic</th>
            <td>Static, defined at compile-time</td>
            <td>Instance method, can use runtime polymorphism</td>
        </tr>
    </tbody>
</table>



<button class="shbtn" id="shbtn90767" onclick="showHideBlock(90767)">&#9660; <u>Show example</u></button>
<div id="shdiv90767" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>== Operator:</b></div>
<pre class="pchl"><code><span class="com">// Value type comparison</span>
<span class="key">int</span> a = 5;
<span class="key">int</span> b = 5;
Console.WriteLine(a <span style="background:#f2f19d;">==</span> b); <span class="com">// True</span>

<span class="com">// Reference type comparison</span>
<span class="key">object</span> obj1 = <span class="key">new</span> <span class="key">object</span>();
<span class="key">object</span> obj2 = <span class="key">new</span> <span class="key">object</span>();
Console.WriteLine(obj1 <span style="background:#f2f19d;">==</span> obj2); <span class="com">// False (different references)</span>

<span class="key">string</span> str1 = <span class="str">"hello"</span>;
<span class="key">string</span> str2 = <span class="str">"hello"</span>;
Console.WriteLine(str1 <span style="background:#f2f19d;">==</span> str2); <span class="com">// True (string interning in C#)</span></code></pre>



<br><br>
<div style="padding-left: 0.3125rem;"><b>Equals Method:</b></div>
<pre class="pchl"><code><span class="com">// Value type comparison</span>
<span class="key">int</span> a = 5;
<span class="key">int</span> b = 5;
Console.WriteLine(a.<span style="background:#f2f19d;">Equals</span>(b)); <span class="com">// True</span>

<span class="com">// Reference type comparison</span>
<span class="key">object</span> obj1 = <span class="key">new</span> <span class="key">object</span>();
<span class="key">object</span> obj2 = <span class="key">new</span> <span class="key">object</span>();
Console.WriteLine(obj1.<span style="background:#f2f19d;">Equals</span>(obj2)); <span class="com">// False (different references)</span>

<span class="key">string</span> str1 = <span class="str">"hello"</span>;
<span class="key">string</span> str2 = <span class="str">"hello"</span>;
Console.WriteLine(str1.<span style="background:#f2f19d;">Equals</span>(str2)); <span class="com">// True (compares the content of strings)</span></code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you override the Equals method in C#?</strong></h3>



<p class="custp1 p-mb-0">Overriding the <span class="spanHT">Equals</span> method involves providing a custom implementation that defines how instances of your class should be compared for equality.</p>



<p class="custp1 p-mb-0"><strong><em>Steps to Override Equals Method</em>:</strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Override the Equals Method &#8211; </strong>Provide a custom implementation for the <span class="spanHT">Equals</span> method that compares the relevant fields of your object.</li>



<li><strong>Override GetHashCode Method &#8211; </strong>When overriding <span class="spanHT">Equals</span>, it is also important to override <span class="spanHT">GetHashCode</span> to ensure that objects that are considered equal have the same hash code.</li>



<li><strong>Implement IEquatable&lt;T&gt; Interface</strong> (Optional) &#8211; Implementing <span class="spanHT">IEquatable&lt;T&gt;</span> can improve performance and make your equality checks more explicit.</li>
</ol>



<button class="shbtn" id="shbtn87874" onclick="showHideBlock(87874)">&#9660; <u>Show example</u></button>
<div id="shdiv87874" style="display: none;">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Person <span style="background:#f2f19d;">: IEquatable&lt;Person&gt</span>
{
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> <span class="key">int</span> Age { get; set; }

    <span class="com">// Override the Equals method</span>
    <span style="background:#f2f19d;"><span class="key">public</span> <span class="key">override</span> <span class="key">bool</span> Equals(<span class="key">object</span> obj)</span>
    {
        <span class="com">// If the object is null or not of the same type, return false</span>
        <span class="key">if</span> (obj == <span class="key">null</span> || this.GetType() != obj.GetType())
        {
            <span class="key">return</span> false;
        }

        <span class="com">// Cast the object to Person and compare the properties</span>
        Person other = (Person)obj;
        <span class="key">return</span> this.Name == other.Name && this.Age == other.Age;
    }

    <span class="com">// Override GetHashCode method</span>
    <span style="background:#f2f19d;"><span class="key">public</span> <span class="key">override</span> <span class="key">int</span> GetHashCode()</span>
    {
        <span class="com">// Combine the hash codes of the properties</span>
        <span class="key">return</span> (Name?.GetHashCode() ?? 0) ^ Age.GetHashCode();
    }

    <span class="com">// Implement IEquatable<Person> interface</span>
    <span class="key">public</span> <span class="key">bool</span> Equals(Person other)
    {
        <span class="com">// If the other object is null, return false</span>
        <span class="key">if</span> (other == <span class="key">null</span>)
        {
            <span class="key">return</span> false;
        }

        <span class="com">// Compare the properties</span>
        <span class="key">return</span> this.Name == other.Name && this.Age == other.Age;
    }

    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        Person person1 = <span class="key">new</span> Person { Name = <span class="str">"Alice"</span>, Age = 30 };
        Person person2 = <span class="key">new</span> Person { Name = <span class="str">"Alice"</span>, Age = 30 };
        Person person3 = <span class="key">new</span> Person { Name = <span class="str">"Bob"</span>, Age = 25 };

        Console.WriteLine(person1.Equals(person2)); <span class="com">// True</span>
        Console.WriteLine(person1.Equals(person3)); <span class="com">// False</span>
        Console.WriteLine(person1.GetHashCode() == person2.GetHashCode()); <span class="com">// True</span>
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement the IComparable&lt;T&gt; interface?</strong></h3>



<p class="custp1 p-mb-0"><span class="spanHT">IComparable&lt;T&gt;</span> is particularly useful for sorting and comparison operations. The interface requires you to implement the <span class="spanHT">CompareTo</span> method, which compares the current instance with another object of the same type.</p>



<button class="shbtn" id="shbtn21248" onclick="showHideBlock(21248)">&#9660; <u>Show example</u></button>
<div id="shdiv21248" style="display: none;" class="shdt">

<pre class="pchl"><code><span class="key">using</span> System;
<span class="key">using</span> System.Collections.Generic;

<span class="key">public</span> <span class="key">class</span> Person <span style="background:#f2f19d;">: IComparable&lt;Person&gt</span>
{
    <span class="key">public</span> <span class="key">string</span> Name { get; set; }
    <span class="key">public</span> <span class="key">int</span> Age { get; set; }

    <span class="com">// Implement the CompareTo method</span>
    <span class="key">public</span> <span class="key">int</span> <span style="background:#f2f19d;">CompareTo(Person other)</span>
    {
        <span class="key">if</span> (other == <span class="key">null</span>)
        {
            <span class="key">return</span> 1;
        }

        <span class="com">// Compare the Age properties</span>
        <span class="key">return</span> this.Age.CompareTo(other.Age);
    }

    <span class="key">public</span> <span class="key">override</span> <span class="key">string</span> ToString()
    {
        <span class="key">return</span> $<span class="str">"{Name}, Age: {Age}"</span>;
    }

    <span class="key">public</span> <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        List&lt;Person&gt people = <span class="key">new</span> List&lt;Person&gt
        {
            <span class="key">new</span> Person { Name = <span class="str">"Alice"</span>, Age = 30 },
            <span class="key">new</span> Person { Name = <span class="str">"Bob"</span>, Age = 25 },
            <span class="key">new</span> Person { Name = <span class="str">"Charlie"</span>, Age = 35 }
        };

        <span class="com">// Sort the list using the <b>CompareTo</b> method</span>
        people<span style="background:#f2f19d;">.Sort()</span>;

        <span class="com">// Display the sorted list</span>
        <span class="key">foreach</span> (<span class="key">var</span> person <span class="key">in</span> people)
        {
            Console.WriteLine(person);
        }
    }
} </code></pre>

<br>
<div style="padding-left: 0.3125rem; padding-bottom: 0.3125rem;">The <b>Sort</b> method of <b>List&lt;T&gt;</b> uses the <span class="spanHT">CompareTo</span> method to sort the Person objects by age.</b></div>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the &#8216;global&#8217; keyword in namespace declarations?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">global</span> keyword is used in namespace declarations to reference the global namespace, ensuring that the namespace reference is unambiguous and starts from the root. This is particularly useful in scenarios where you might have nested or conflicting namespaces and it makes the code clearer.</p>



<button class="shbtn" id="shbtn27490" onclick="showHideBlock(27490)">&#9660; <u>Show example</u></button>
<div id="shdiv27490" style="display: none;">
<pre class="pchl"><code><span class="key">namespace</span> MyCompany.Project
{
    <span class="key">class</span> Program
    {
        <span class="key">static</span> <span class="key">void</span> Main(string[] args)
        {
            <span class="com">// Using <b>global::System</b> ensures the System namespace from the root</span>
            <span class="key" style="background:#f2f19d;">global::</span>System.Console.WriteLine(<span class="str">"Hello, World!"</span>);
        }
    }
} </code></pre>
</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are &#8216;global using&#8217; directives in C# 10.0?</strong></h3>



<p class="custp1"><strong>Global using directives</strong> are a C# 10.0 feature that allows <span class="spanHT">using</span> directives to be declared once and applied globally to all files in a project. They simplify and clean up code by reducing the need for repetitive <span class="spanHT">using</span> statements.</p>



<pre class="pchl"><code><span class="key">global</span> <span class="key">using</span> System;
<span class="key">global</span> <span class="key">using</span> System.Collections.Generic;
<span class="key">global</span> <span class="key">using</span> System.Linq; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Dependency Injection and How do you implement it in different ways in C#?</strong></h3>



<p class="custp1">Dependency Injection (DI) is a design pattern used to achieve Inversion of Control (IoC) between classes and their dependencies. It allows the dependencies of a class to be injected at runtime, promoting decoupling and easier testing.</p>



<p class="p-mb-0"><strong><em>Key Components of Dependency Injection:</em></strong></p>



<ol class="ol1 wp-block-list">
<li><strong>Service</strong>: The class that performs some specific service.</li>



<li><strong>Client</strong>: The class that depends on the service.</li>



<li><strong>Injector</strong>: The mechanism that injects the service into the client.</li>
</ol>



<p class="p-mb-0"><strong><em>3 Ways to Implement Dependency Injection:</em></strong></p>



<ol class="ol1 ol1-mb-0">

<li class="custp1"><strong>Constructor Injection</strong>: Dependencies are provided through a class constructor. This is the most commonly used type of dependency injection.</li>
<button class="shbtn" style="margin-top:0" id="shbtn54509" onclick="showHideBlock(54509)">&#9660; <u>Show example</u></button>
<div id="shdiv54509" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Step 1: Define the Service Interface</b></div>
<pre class="pchl"><code><span class="key">public</span> <span style="background:#f2f19d;"><span class="key">interface</span> IMessageService</span>
{
    <span class="key">void</span> SendMessage(<span class="key">string</span> message);
} </code></pre>


<br>
<div style="padding-left: 0.3125rem;"><b>Step 2: Implement the Service</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> EmailService <span style="background:#f2f19d;">: IMessageService</span>
{
    <span class="key">public</span> <span class="key">void</span> SendMessage(<span class="key">string</span> message)
    {
        Console.WriteLine(<span class="str">"Email message: "</span> + message);
    }
} </code></pre>


<br>
<div style="padding-left: 0.3125rem;"><b>Step 3: Define the Client</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Notification
{
    <span style="background:#f2f19d;"><span class="key">private</span> <span class="key">readonly</span> IMessageService _messageService;</span>

    <span class="com">// <b>Constructor Injection</b></span>
    <span style="background:#f2f19d;"><span class="key">public</span> Notification(IMessageService messageService)
    {
        _messageService = messageService;
    }</span>

    <span class="key">public</span> <span class="key">void</span> Notify(<span class="key">string</span> message)
    {
        _messageService.SendMessage(message);
    }
} </code></pre>
<div class="custp1" style="padding-left: 0.3125rem;">&#8216;Notification&#8217; depends on &#8216;IMessageService&#8217; and gets it through constructor injection.</div>

<br>
<div style="padding-left: 0.3125rem;"><b>Step 4: Set Up Dependency Injection</b>
<br>Using a DI container like Microsoft.Extensions.DependencyInjection</div>
<pre class="pchl"><code><span class="key">using</span> Microsoft.Extensions.DependencyInjection;

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="com">// </b>Set up the DI container</b></span>
        <span class="key">var</span> serviceProvider = <span class="key">new</span> ServiceCollection()
            <span style="background:#f2f19d;">.AddTransient&lt;IMessageService, EmailService&gt()</span>
            .AddTransient&lt;Notification&gt()
            .BuildServiceProvider();

        <span class="com">// Resolve the dependency</span>
        <span class="key">var</span> notification = serviceProvider.GetService&lt;Notification&gt();
        notification.Notify(<span class="str">"Hello, Dependency Injection!"</span>);
    }
} </code></pre>
</div>



<li class="custp1"><strong>Property Injection</strong>: Dependencies are provided through public properties of the client class. This type is less commonly used and typically for optional dependencies.</li>
<button class="shbtn" style="margin-top:0" id="shbtn65054" onclick="showHideBlock(65054)">&#9660; <u>Show example</u></button>
<div id="shdiv65054" style="display: none;">
<pre class="pchl"><code><span class="com"><b>// Step 1:</b></span>
<span class="key">public</span> <span style="background:#f2f19d;"><span class="key">interface</span> IService</span>
{
    <span class="key">void</span> Serve();
}


<span class="com"><b>// Step 2:</b></span>
<span class="key">public</span> <span class="key">class</span> Service <span style="background:#f2f19d;">: IService</span>
{
    <span class="key">public</span> <span class="key">void</span> Serve()
    {
        Console.WriteLine(<span class="str">"Service Called"</span>);
    }
}


<span class="com"><b>// Step 3:</b></span>
<span class="key">public</span> <span class="key">class</span> Client
{
    <span class="com"><b>// Property Injection</b></span>
    <span style="background:#f2f19d;"><span class="key">public</span> IService Service { get; set; }</span>

    <span class="key">public</span> <span class="key">void</span> Start()
    {
        <span style="background:#f2f19d;">Service?.Serve();</span>
    }
}


<span class="com"><b>// Step 4:</b> Setting up the DI container</span>
<span class="key">var</span> serviceProvider = <span class="key">new</span> ServiceCollection()
    <span style="background:#f2f19d;">.AddTransient&lt;IService, Service&gt()</span>
    .AddTransient&lt;Client&gt()
    .BuildServiceProvider();

<span class="com">// Resolving the dependency</span>
<span class="key">var</span> client = serviceProvider.GetService&lt;Client&gt();
client.Service = serviceProvider.GetService&lt;IService&gt();
client.Start(); </code></pre>
</div>




<li class="custp1"><strong>Method Injection</strong>: Dependencies are provided through method parameters. This type is used when the dependency is only needed for a specific method.</li>
<button class="shbtn" style="margin-top:0" id="shbtn75553" onclick="showHideBlock(75553)">&#9660; <u>Show example</u></button>
<div id="shdiv75553" style="display: none;">
<pre class="pchl"><code><span class="com"><b>// Step 1:</b></span>
<span class="key">public</span> <span style="background:#f2f19d;"><span class="key">interface</span> IService</span>
{
    <span class="key">void</span> Serve();
}


<span class="com"><b>// Step 2:</b></span>
<span class="key">public</span> <span class="key">class</span> Service <span style="background:#f2f19d;">: IService</span>
{
    <span class="key">public</span> <span class="key">void</span> Serve()
    {
        Console.WriteLine(<span class="str">"Service Called"</span>);
    }
}


<span class="com"><b>// Step 3:</b></span>
<span class="key">public</span> <span class="key">class</span> Client
{
    <span class="com"><b>// Method Injection</b></span>
    <span style="background:#f2f19d;"><span class="key">public</span> <span class="key">void</span> Start(IService service)
    {
        service.Serve();
    }</span>
}


<span class="com"><b>// Step 4:</b> Setting up the DI container</span>
<span class="key">var</span> serviceProvider = <span class="key">new</span> ServiceCollection()
    <span style="background:#f2f19d;">.AddTransient&lt;IService, Service&gt()</span>
    .AddTransient&lt;Client&gt()
    .BuildServiceProvider();

<span class="com">// Resolving the dependency</span>
<span class="key">var</span> client = serviceProvider.GetService&lt;Client&gt();
<span class="key">var</span> service = serviceProvider.GetService&lt;IService&gt();
client.Start(service); </code></pre>
</div>

</ol>
<br>



<p class="p-mb-0"><strong><em>Advantages:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Decoupling</strong>: Reduces tight coupling between classes.</li>



<li><strong>Testability</strong>: Makes it easier to test by allowing mock implementations.</li>



<li><strong>Flexibility</strong>: Promotes flexible and maintainable code architecture.</li>
</ul>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use the Activator.CreateInstance method?</strong></h3>



<p class="custp1 p-mb-0"><span class="spanHT">Activator.CreateInstance</span> allows you to create instances of types at runtime. This method is particularly useful when the type of the object to be created is not known at compile time but is determined at runtime. It provides several overloads to support different scenarios, such as creating instances with parameters or using generic type parameters.</p>



<button class="shbtn" id="shbtn66564" onclick="showHideBlock(66564)">&#9660; <u>Show example</u></button>
<div id="shdiv66564" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Example shows 4 ways to use the Activator.CreateInstance method</b></div>

<pre class="pchl"><code><span class="key">public</span> <span class="key">interface</span> IMyInterface
{
    <span class="key">void</span> Display();
}

<span class="key">public</span> <span class="key">class</span> MyClass : IMyInterface
{
    <span class="key">public</span> <span class="key">void</span> Display()
    {
        Console.WriteLine(<span class="str">"MyClass instance created implementing IMyInterface!"</span>);
    }
}

<span class="key">public</span> <span class="key">class</span> MyClass2
{
    <span class="key">public</span> MyClass2(<span class="key">string</span> message)
    {
        Console.WriteLine(message);
    }
	
	<span class="key">public</span> <span class="key">void</span> Display2()
    {
        Console.WriteLine(<span class="str">"MyClass2 instance created!"</span>);
    }
	
	
}

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// <span style="background:#f2f19d;"><b>Method 1</b>:</span> Create an instance of MyClass <span style="background:#f2f19d;">(Basic Usage)</span></span>
        <span class="key">var</span> myClassInstance1 = (MyClass2)Activator.CreateInstance(<span class="key">typeof</span>(MyClass2));
        myClassInstance1.Display2();
		
		
        <span class="com">// <span style="background:#f2f19d;"><b>Method 2:</b></span> Create an instance of MyClass <span style="background:#f2f19d;">using generic overload</span></span>
        <span class="key">var</span> myClassInstance2 = Activator.CreateInstance&lt;MyClass2&gt();
        myClassInstance2.Display2();
		
		
        <span class="com">// <span style="background:#f2f19d;"><b>Method 3:</b></span> Create an instance of MyClass <span style="background:#f2f19d;">with parameter</span></span>
        <span class="key">var</span> myClassInstance3 = (MyClass2)Activator.CreateInstance(<span class="key">typeof</span>(MyClass2), <span class="str">"Hello, MyClass!"</span>);
		
		
        <span class="com">// <span style="background:#f2f19d;"><b>Method 4:</b></span> Create an instance of MyClass type <span style="background:#f2f19d;">implementing Interfaces</span></span>
        <span class="key">var</span> myClassInstance4 = (IMyInterface)Activator.CreateInstance(<span class="key">typeof</span>(MyClass));
        myClassInstance4.Display();
		
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use pattern matching in C#?</strong></h3>



<p class="custp1 p-mb-0">Pattern matching can be used with <span class="spanHT">switch</span> statements, <span class="spanHT">if</span> statements, and expressions. Pattern matching enhances type safety and readability, making code more expressive and easier to maintain.</p>



<button class="shbtn" id="shbtn77669" onclick="showHideBlock(77669)">&#9660; <u>Show example</u></button>
<div id="shdiv77669" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>1) Pattern Matching with &#39;if&#39; and &#39;is&#39; Keyword:</b></div>
<pre class="pchl"><code><span class="key">object</span> obj = <span class="str">"Hello, World!"</span>;
<span class="key">if</span> (obj <span class="key">is</span> <span class="key">string</span> s)
{
    Console.WriteLine($<span class="str">"The string is: {s}"</span>);
} </code></pre>



<br><br>
<div style="padding-left: 0.3125rem;"><b>2) Pattern Matching in &#39;switch&#39; Statements:</b></div>
<pre class="pchl"><code><span class="key">object</span> obj = 42;

<span class="key">switch</span> (obj)
{
    <span class="key">case</span> <span class="key">int</span> i:
        Console.WriteLine($<span class="str">"The integer is: {i}"</span>);
        <span class="key">break</span>;
    <span class="key">case</span> <span class="key">string</span> s:
        Console.WriteLine($<span class="str">"The string is: {s}"</span>);
        <span class="key">break</span>;
    <span class="key">default</span>:
        Console.WriteLine(<span class="str">"Unknown type"</span>);
        <span class="key">break</span>;
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>3) Relational Patterns and Logical Patterns:</b>
<br>
C# 9.0 introduced relational and logical patterns, allowing for more complex pattern matching scenarios.
</div>
<pre class="pchl"><code><span class="key">int</span> number = 42;

<span class="key">string</span> description = number <span class="key">switch</span>
{
    &lt; 0 =&gt <span class="str">"Negative"</span>,
    0 =&gt <span class="str">"Zero"</span>,
    &gt 0 and &lt;= 10 =&gt <span class="str">"Small positive number"</span>,
    &gt 10 =&gt <span class="str">"Large positive number"</span>,
    _ =&gt <span class="str">"Unknown"</span>
};

Console.WriteLine(description); <span class="com">// Output: Large positive number</span></code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>4) Tuple Pattern Matching:</b>
<br>
You can use pattern matching with tuples to match multiple values at once.
</div>
<pre class="pchl"><code>(<span class="key">int</span> x, <span class="key">int</span> y) point = (1, 2);

<span class="key">string</span> quadrant = point <span class="key">switch</span>
{
    (0, 0) =&gt <span class="str">"Origin"</span>,
    <span class="key">var</span> (x, y) when x &gt 0 && y &gt 0 =&gt <span class="str">"Quadrant I"</span>,
    <span class="key">var</span> (x, y) when x &lt; 0 && y &gt 0 =&gt <span class="str">"Quadrant II"</span>,
    <span class="key">var</span> (x, y) when x &lt; 0 && y &lt; 0 =&gt <span class="str">"Quadrant III"</span>,
    <span class="key">var</span> (x, y) when x &gt 0 && y &lt; 0 =&gt <span class="str">"Quadrant IV"</span>,
    _ =&gt <span class="str">"On axis"</span>
};

Console.WriteLine(quadrant); <span class="com">// Output: Quadrant I</span></code></pre>



<br><br>
<div style="padding-left: 0.3125rem;"><b>5) Positional Pattern Matching:</b>
<br>
Positional pattern matching is useful with deconstructable types, such as tuples or custom types with a Deconstruct method.
</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Point
{
    <span class="key">public</span> <span class="key">int</span> X { get; }
    <span class="key">public</span> <span class="key">int</span> Y { get; }
    <span class="key">public</span> Point(<span class="key">int</span> x, <span class="key">int</span> y) =&gt (X, Y) = (x, y);
    <span class="key">public</span> <span class="key">void</span> Deconstruct(<span class="key">out</span> <span class="key">int</span> x, <span class="key">out</span> <span class="key">int</span> y) =&gt (x, y) = (X, Y);
}

<span class="key">var</span> point = <span class="key">new</span> Point(1, 2);

<span class="key">string</span> location = point <span class="key">switch</span>
{
    (0, 0) =&gt <span class="str">"Origin"</span>,
    <span class="key">var</span> (x, y) when x &gt 0 && y &gt 0 =&gt <span class="str">"Quadrant I"</span>,
    <span class="key">var</span> (x, y) when x &lt; 0 && y &gt 0 =&gt <span class="str">"Quadrant II"</span>,
    <span class="key">var</span> (x, y) when x &lt; 0 && y &lt; 0 =&gt <span class="str">"Quadrant III"</span>,
    <span class="key">var</span> (x, y) when x &gt 0 && y &lt; 0 =&gt <span class="str">"Quadrant IV"</span>,
    _ =&gt <span class="str">"On axis"</span>
};

Console.WriteLine(location); <span class="com">// Output: Quadrant I</span></code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of tuples in C#?</strong></h3>



<p class="custp1 p-mb-0">Tuples provide a way to store multiple values in a single object without creating a custom class or struct. They are useful for returning multiple values from a method, grouping related data, and making code more readable and concise.</p>



<button class="shbtn" id="shbtn15262" onclick="showHideBlock(15262)">&#9660; <u>Show example</u></button>
<div id="shdiv15262" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem; color:#ff0000;"><b>Usages Without tuples</b>, returning multiple values from a method often requires using out parameters:
</div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> GetCoordinates(<span class="key">out</span> <span class="key">int</span> x, <span class="key">out</span> <span class="key">int</span> y)
{
    x = 10;
    y = 20;
}

<span class="key">int</span> x, y;
GetCoordinates(<span class="key">out</span> x, <span class="key">out</span> y);
Console.WriteLine($<span class="str">"x: {x}, y: {y}"</span>);</code></pre>

<br><br><br>
<div><b>Usages With tuples</b>, the same functionality can be achieved more concisely:</div>
<pre class="pchl"><code><span class="key">public</span> <span style="background:#f2f19d;">(<span class="key">int</span>, <span class="key">int</span>)</span> GetCoordinates()
{
    <span class="key">return</span> (10, 20);
}

<span class="key">var</span> coordinates = GetCoordinates();
Console.WriteLine($<span class="str">"x: {coordinates.Item1}, y: {coordinates.Item2}"</span>);</code></pre>


<br><br><br>
<div style="padding-left: 0.3125rem;"><b>Named Tuples</b>
<br>
Tuples can have named elements, which improve code readability:
</div>
<pre class="pchl"><code><span class="key">public</span> <span style="background:#f2f19d;">(<span class="key">int</span> X, <span class="key">int</span> Y)</span> GetCoordinates()
{
    <span class="key">return</span> (10, 20);
}

<span class="key">var</span> coordinates = GetCoordinates();
Console.WriteLine($<span class="str">"x: {coordinates.X}, y: {coordinates.Y}"</span>);</code></pre>



<br><br><br>
<div style="padding-left: 0.3125rem;"><b>Grouping Related Data</b>
<br>
Tuples are useful for grouping data without creating a separate class:
</div>
<pre class="pchl"><code><span class="key">var</span> person = <span style="background:#f2f19d;">(<span class="str">"John"</span>, <span class="str">"Doe"</span>, 30)</span>;

Console.WriteLine($<span class="str">"First Name: {person.Item1}"</span>);
Console.WriteLine($<span class="str">"Last Name: {person.Item2}"</span>);
Console.WriteLine($<span class="str">"Age: {person.Item3}"</span>);</code></pre>

<br>
<div>Using named tuples improves readability:</div>
<pre class="pchl"><code><span class="key">var</span> person = <span style="background:#f2f19d;">(FirstName: <span class="str">"John"</span>, LastName: <span class="str">"Doe"</span>, Age: 30)</span>;

Console.WriteLine($<span class="str">"First Name: {person.FirstName}"</span>);
Console.WriteLine($<span class="str">"Last Name: {person.LastName}"</span>);
Console.WriteLine($<span class="str">"Age: {person.Age}"</span>);</code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you deconstruct a tuple in C#?</strong></h3>



<p class="custp1 p-mb-0">Deconstruction extracts the elements of the tuple into individual variables. You can deconstruct a tuple into separate variables to make it easier to work with the individual elements.</p>



<button class="shbtn" id="shbtn94992" onclick="showHideBlock(94992)">&#9660; <u>Show example</u></button>
<div id="shdiv94992" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Basic Deconstruction:</b></div>
<pre class="pchl"><code><span class="com">// Creating a tuple</span>
<span class="key">var</span> person = (<span class="str">"John"</span>, <span class="str">"Doe"</span>, 30);

<span class="com">// Deconstructing the tuple into individual variables</span>
<span style="background:#f2f19d;">(<span class="key">string</span> firstName, <span class="key">string</span> lastName, <span class="key">int</span> age) = <b>person</b>;</span>

Console.WriteLine($<span class="str">"First Name: {firstName}"</span>);
Console.WriteLine($<span class="str">"Last Name: {lastName}"</span>);
Console.WriteLine($<span class="str">"Age: {age}"</span>); </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Named Tuple Deconstruction:</b></div>
<pre class="pchl"><code><span class="com">// Creating a named tuple</span>
<span class="key">var</span> person = (FirstName: <span class="str">"John"</span>, LastName: <span class="str">"Doe"</span>, Age: 30);

<span class="com">// Deconstructing the named tuple into individual variables</span>
<span style="background:#f2f19d;">(<span class="key">string</span> firstName, <span class="key">string</span> lastName, <span class="key">int</span> age) = <b>person</b>;</span> </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Deconstructing Directly in Method Calls:</b></div>
<pre class="pchl"><code><span class="com">// Method returning a tuple</span>
<span class="key">public</span> (<span class="key">string</span> FirstName, <span class="key">string</span> LastName, <span class="key">int</span> Age) <span style="background:#f2f19d;">GetPerson()</span>
{
    <span class="key">return</span> (<span class="str">"John"</span>, <span class="str">"Doe"</span>, 30);
}

<span class="com">// Deconstructing the tuple returned by the method</span>
<span class="key">var</span> (firstName, lastName, age) = <span style="background:#f2f19d;"><b>GetPerson()</b></span>; </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Using Discards (_):</b>
<br>
you can use discards (_) for the elements you don&#8217;t need.
</div>
<pre class="pchl"><code><span class="key">var</span> person = (<span class="str">"John"</span>, <span class="str">"Doe"</span>, 30);

<span class="com">// Deconstructing and discarding the last name</span>
<span style="background:#f2f19d;">(<span class="key">string</span> firstName, _, <span class="key">int</span> age) = <b>person</b></span>;

Console.WriteLine($<span class="str">"First Name: {firstName}"</span>);
Console.WriteLine($<span class="str">"Age: {age}"</span>); </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What happens if a constructor throws an exception in C#?</strong></h3>



<p class="custp1 p-mb-0">When a constructor throws an exception, the object construction fails and the following things happen:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Object Creation Fails:</strong> <em>The partially created object is discarded</em>, and the reference to the object becomes <span class="spanHT">null</span> (if the constructor was called with the <span class="spanHT">new</span> keyword).</li>



<li><strong>Exception Propagation:</strong> <em>The exception propagates up the call stack</em> to the point where the constructor was called. If not caught, it continues to propagate until it is either caught by a <span class="spanHT">catch</span> block or the application terminates.</li>



<li><strong>No Finalizers Called:</strong> <em>Finalizers (destructors) are not called</em> on the partially constructed object because it was never fully constructed. The garbage collector will eventually clean up any resources associated with the object.</li>
</ul>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is an anonymous method in C#?</strong></h3>



<p class="custp1 p-mb-0">An anonymous method in C# is a method without a name, defined using the <span class="spanHT">delegate</span> keyword. It allows you to define inline methods that can be passed as parameters, used in event handling, or assigned to delegates without needing to declare a separate method.</p>



<button class="shbtn" id="shbtn35696" onclick="showHideBlock(35696)">&#9660; <u>Show example</u></button>
<div id="shdiv35696" style="display: none;">

<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">delegate</span> <span class="key">void</span> MyDelegate(<span class="key">string</span> message);

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main(string[] args)
    {
        <span class="com">// Anonymous method assigned to a delegate</span>
        MyDelegate myDelegate = <span class="key">delegate</span> (<span class="key">string</span> msg)
        {
            Console.WriteLine(msg);
        };

        <span class="com">// Invoke the delegate</span>
        myDelegate(<span class="str">"Hello, this is an anonymous method!"</span>);
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the &#8216;nameof&#8217; operator in C#?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">nameof</span> operator is used to obtain the name of a variable, type, or member as a string. It is useful for refactoring, code readability, and avoiding hardcoded strings, especially when dealing with exceptions, logging, or argument validation.</p>



<pre class="pchl"><code><span class="key">string</span> propertyName = <span class="key" style="background:#f2f19d;">nameof</span>(Example.PropertyName); </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are expression-bodied members in C#?</strong></h3>



<p class="custp1 p-mb-0">Expression-bodied members in C# provide a concise syntax for defining methods, properties, constructors, destructors, and other members that can be implemented with a single expression. Expression-bodied members use the <span class="spanHT">=&gt;</span> (lambda expression) syntax to directly return or assign a value. </p>



<p class="custp1 p-mb-0"><strong><em>Traditional method syntax:</em></strong></p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">int</span> Add(<span class="key">int</span> x, <span class="key">int</span> y)
{
	<span class="key">return</span> x + y;
}</code></pre>
<br>



<p class="p-mb-0"><strong><em>Expression-bodied method</em>:</strong></p>



<pre class="pchl"><code><span class="key">public</span> <span class="key">int</span> AddExpressionBodied(<span class="key">int</span> x, <span class="key">int</span> y) <span style="background:#f2f19d;">=&gt</span> x + y; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the Span&lt;T&gt; type in C#?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">Span&lt;T&gt;</span> type provides a safe and efficient way to work with contiguous memory regions. It is a stack-allocated type, meaning it&#8217;s a lightweight, value type that helps avoid heap allocations. <span class="spanHT">Span&lt;T&gt;</span> is particularly useful in scenarios requiring high performance and low memory overhead, such as processing large data streams or performing operations on buffers, systems programming, game development, or processing large datasets. </p>



<p class="custp1 p-mb-0">Allows for creating sub-spans (slices) of the original span without copying data, providing a view over a portion of the memory. </p>



<p class="custp1 p-mb-0"><span class="spanHT">ReadOnlySpan&lt;T&gt;</span> is a read-only counterpart, used when you need a non-modifiable view of the data. </p>



<button class="shbtn" id="shbtn566" onclick="showHideBlock(566)">&#9660; <u>Show example</u></button>
<div id="shdiv566" style="display: none;">

<pre class="pchl"><code><span class="key">using</span> System;

<span class="key">class</span> Program
{
    <span class="key">static</span> <span class="key">void</span> Main()
    {
        <span class="com">// Example with an array</span>
        int[] numbers = { 1, 2, 3, 4, 5 };

        <span class="com">// Create a Span over the array</span>
        <span style="background:#f2f19d;"><span class="custkey">Span</span>&lt;<span class="key">int</span>&gt</span> span = numbers;

        <span class="com">// Modify the span (and thus the array)</span>
        span[2] = 100;

        <span class="com">// Print the modified array</span>
        <span class="key">foreach</span> (<span class="key">var</span> number <span class="key">in</span> numbers)
        {
            Console.WriteLine(number);
        }

        <span class="com">// Output: 1, 2, 100, 4, 5</span>

        <span class="com">// Slicing a Span</span>
        <span style="background:#f2f19d;"><span class="custkey">Span</span>&lt;<span class="key">int</span>&gt</span> slice = span.Slice(1, 3);

        <span class="com">// Print the sliced span</span>
        <span class="key">foreach</span> (<span class="key">var</span> item <span class="key">in</span> slice)
        {
            Console.WriteLine(item);
        }

        <span class="com">// Output: 2, 100, 4</span>
    }
} </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the &#8216;stackalloc&#8217; keyword in C#?</strong></h3>



<p class="custp1 p-mb-0">The <strong>stackalloc</strong> keyword is used to allocate memory on the stack for temporary arrays or spans. It improves performance by avoiding heap allocations (which is faster and more efficient) and reducing garbage collection overhead.</p>



<pre class="pchl"><code><span class="custkey">Span</span>&lt;<span class="key">int</span>&gt numbers = <span class="key" style="background:#f2f19d;">stackalloc</span> <span class="key">int</span>[5];
<span class="com">// or</span>
<span class="custkey">Span</span>&lt;<span class="key">int</span>&gt numbers = <span class="key" style="background:#f2f19d;">stackalloc</span> <span class="key">int</span>[3] { 10, 20, 30 }; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of Memory&lt;T&gt; and ReadOnlyMemory&lt;T&gt;?</strong></h3>



<p class="custp1 p-mb-0"><span class="spanHT">Memory&lt;T&gt;</span> and <span class="spanHT">ReadOnlyMemory&lt;T&gt;</span> are types designed to represent a contiguous region of memory in a safe and efficient manner. They allow for working with large data buffers, slices of arrays, or other memory blocks without the need for copying data. They are especially useful in performance-critical applications where minimizing memory allocations and copying is important. </p>



<p class="custp1 p-mb-0"><strong><em>Purpose of Memory&lt;T&gt;:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Writable Memory</strong>: Memory&lt;T&gt; represents a block of memory that can be read from and written to. It is similar to Span&lt;T&gt;, but Memory&lt;T&gt; can be stored on the heap, while Span&lt;T&gt; is restricted to stack-only scenarios.</li>



<li><strong>Slicing</strong>: Allows you to create sub-slices of the memory without copying the underlying data.</li>



<li><strong>Asynchronous (<strong>Async/Await</strong></strong>)<strong> Operations</strong>: Unlike Span&lt;T&gt;, Memory&lt;T&gt; can be used in async methods. Efficiently manage buffers in scenarios like network I/O, file I/O, or data processing where copying data would be costly.</li>
</ul>



<p class="custp1 p-mb-0"><strong><em>Purpose of ReadOnlyMemory&lt;T&gt;:</em></strong></p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Read-Only Memory</strong>: ReadOnlyMemory&lt;T&gt; is similar to Memory&lt;T&gt;, but it only allows reading from the memory. It ensures that the underlying data cannot be modified, which is useful for enforcing immutability.</li>



<li><strong>Data Security</strong>: Provides a way to pass around slices of data safely, ensuring that the original data cannot be altered by the recipient.</li>



<li><strong>Immutable Data</strong>: Use ReadOnlyMemory&lt;T&gt; when you want to ensure that a section of data remains unchanged when passed to other parts of the code.</li>
</ul>



<button class="shbtn" id="shbtn23407" onclick="showHideBlock(23407)">&#9660; <u>Show example</u></button>
<div id="shdiv23407" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Syntax:</b></div>
<pre class="pchl"><code><span style="background:#f2f19d;"><span class="custkey">Memory</span>&lt;<span class="key">int</span>&gt</span> memory = <span class="key">new</span> int[] { 1, 2, 3 };
<span style="background:#f2f19d;"><span class="custkey">ReadOnlyMemory</span>&lt;<span class="key">int</span>&gt</span> readOnlyMemory = <span class="key">new</span> int[] { 1, 2, 3 }; </code></pre>

<br><br>
<div style="padding-left: 0.3125rem;"><b>Memory&lt;T&gt; Example:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> ProcessData(<span style="background:#f2f19d;"><span class="custkey">Memory</span>&lt;<span class="key">byte</span>&gt</span> buffer)
{
    <span class="key">var</span> slice = buffer.Slice(0, 10); <span class="com">// Slice the first 10 bytes</span>
    <span class="com">// Modify the slice</span>
    slice.Span[0] = 255;
}

byte[] data = <span class="key">new</span> byte[100];

ProcessData(data); <span class="com">// Memory<byte> can implicitly be created from arrays</span></code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>ReadOnlyMemory&lt;T&gt; Example:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">void</span> DisplayData(<span style="background:#f2f19d;"><span class="custkey">ReadOnlyMemory</span>&lt;<span class="key">byte</span>&gt</span> buffer)
{
    <span class="key">var</span> slice = buffer.Slice(0, 10); <span class="com">// Slice the first 10 bytes</span>
    <span class="com">// Process the slice without modifying it</span>
    <span class="key">foreach</span> (<span class="key">var</span> b <span class="key">in</span> slice.Span)
    {
        Console.WriteLine(b);
    }
}

byte[] data = <span class="key">new</span> byte[100];

DisplayData(data); <span class="com">// ReadOnlyMemory<byte> can implicitly be created from arrays</span></code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between &#8216;Task&#8217; and &#8216;ValueTask&#8217; in C#?</strong></h3>



<p class="custp1"><span class="spanHT">Task</span> and <span class="spanHT">ValueTask</span> are both used in C# for representing asynchronous operations, but they serve slightly different purposes and are optimized for different scenarios.</p>



<table>
    <thead>
        <tr>
            <th></th>
            <th>Task</th>
            <th>ValueTask</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Purpose</th>
            <td>Represents an asynchronous operation. Always allocates memory on the heap.</td>
            <td>Represents an asynchronous operation that may or may not involve heap allocation.</td>
        </tr>
        <tr>
            <th>Memory Allocation</th>
            <td>Always allocates memory on the heap, even if the operation is already complete.</td>
            <td>Avoids heap allocation when the result is already available or the operation is simple.</td>
        </tr>
        <tr>
            <th>Return Value</th>
            <td>Cannot directly return a value for a completed operation (must use Task.FromResult).</td>
            <td>Can directly return a result or a Task, optimizing for performance in cases where the result is already available. (frequently-called methods that often return a completed result)</td>
        </tr>
        <tr>
            <th>Reusability</th>
            <td>Task instances are reusable.</td>
            <td>ValueTask should not be awaited more than once or used in multiple continuations.</td>
        </tr>
        <tr>
            <th>Error Handling</th>
            <td>Errors are stored inside the Task.</td>
            <td>Errors are stored inside the ValueTask, similar to Task, but need careful handling to avoid misuse.</td>
        </tr>
        <tr>
            <th>Use Cases</th>
            <td>General-purpose, widely used for async operations or if you expect the operation to involve multiple await/continuation scenarios and you don&#8217;t need to optimize for every possible allocation.</td>
            <td>Best for high-performance scenarios where avoiding allocations is critical, and the result is often synchronous, or the operation is simple.</td>
        </tr>
        <tr>
            <th>Overhead</th>
            <td>Higher overhead due to heap allocation.</td>
            <td>Lower overhead when the operation is synchronous or short-lived.</td>
        </tr>
    </tbody>
</table>



<button class="shbtn" id="shbtn94318" onclick="showHideBlock(94318)">&#9660; <u>Show example</u></button>
<div id="shdiv94318" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Task Example:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">async</span> Task&lt;<span class="key">int</span>&gt GetDataAsync()
{
    <span class="key">await</span> Task.Delay(1000);
    <span class="key">return</span> 42;
} </code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>ValueTask Example:</b></div>
<pre class="pchl"><code><span class="key">public</span> ValueTask&lt;<span class="key">int</span>&gt GetDataAsync(<span class="key">bool</span> quickResult)
{
    <span class="key">if</span> (quickResult)
    {
        <span class="com">// Synchronous, no allocation</span>
        <span class="key">return new</span> ValueTask&lt;<span class="key">int</span>&gt(42); 
    }
    <span class="key">else</span>
    {
        <span class="com">// Asynchronous</span>
        <span class="key">return new</span> ValueTask&lt;<span class="key">int</span>&gt(Task.Delay(1000).ContinueWith(t =&gt 42)); 
    }
} </code></pre>


</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use the &#8216;record&#8217; feature in C# 9.0?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">record</span> feature in C# 9.0 introduces a new reference type that provides built-in functionality for immutable data models with value-based equality, making it easier to create data-centric classes. </p>



<p class="custp1 p-mb-0"><strong><em>Key Features of &#8216;record&#8217;:</em></strong></p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Immutability</strong>: By default, records are immutable, meaning once created, their properties cannot be changed. </li>



<li><strong>Value-Based Equality</strong>: Records compare objects based on their values, not their references, making them ideal for data structures where the value matters more than the identity.</li>



<li><strong>Readability</strong>: Use when you need concise and readable code for defining types that primarily store data.</li>



<li><strong>Concise Syntax</strong>: Records can be declared with a much simpler syntax compared to traditional classes.</li>
</ol>



<button class="shbtn" id="shbtn60719" onclick="showHideBlock(60719)">&#9660; <u>Show example</u></button>
<div id="shdiv60719" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Defining a Record:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key" style="background:#f2f19d;">record</span> Person(<span class="key">string</span> FirstName, <span class="key">string</span> LastName); </code></pre>


<br><br>
<div style="padding-left: 0.3125rem; color:red;"><b>This is equivalent to:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Person
{
    <span class="key">public</span> <span class="key">string</span> FirstName { get; }
    <span class="key">public</span> <span class="key">string</span> LastName { get; }

    <span class="key">public</span> Person(<span class="key">string</span> firstName, <span class="key">string</span> lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    <span class="key">public</span> <span class="key">override</span> <span class="key">bool</span> Equals(<span class="key">object</span> obj) =&gt
        obj <span class="key">is</span> Person person &&
        FirstName == person.FirstName &&
        LastName == person.LastName;

    <span class="key">public</span> <span class="key">override</span> <span class="key">int</span> GetHashCode() =&gt 
        HashCode.Combine(FirstName, LastName);
} </code></pre>


<br><br><br>
<div style="padding-left: 0.3125rem;"><b>Creating and Using Records:</b></div>
<pre class="pchl"><code><span class="key">var</span> person1 = <span class="key">new</span> Person(<span class="str">"John"</span>, <span class="str">"Doe"</span>);
<span class="key">var</span> person2 = <span class="key">new</span> Person(<span class="str">"John"</span>, <span class="str">"Doe"</span>);

<span class="com">// Value-based equality</span>
Console.WriteLine(person1 == person2); <span class="com">// True</span>
Console.WriteLine(person1.Equals(person2)); <span class="com">// True</span></code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Positional Syntax:</b>
<br>
You can access record properties using positional deconstruction.
</div>
<pre class="pchl"><code><span class="key">var</span> (firstName, lastName) = person1;
Console.WriteLine(firstName); <span class="com">// John</span>
Console.WriteLine(lastName);  <span class="com">// Doe</span></code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>With-Expressions:</b>
<br>
To create a new record based on an existing one with some modifications.
</div>
<pre class="pchl"><code><span class="key">var</span> person3 = person1 <span class="key">with</span> { LastName = <span class="str">"Smith"</span> };
Console.WriteLine(person3); <span class="com">// Person { FirstName = John, LastName = Smith }</span></code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>Inheritance with Records:</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key" style="background:#f2f19d;">record</span> Employee(<span class="key">string</span> FirstName, <span class="key">string</span> LastName, <span class="key">string</span> Position)
    : Person(FirstName, LastName);

<span class="key">var</span> employee = <span class="key">new</span> Employee(<span class="str">"Jane"</span>, <span class="str">"Doe"</span>, <span class="str">"Manager"</span>);
Console.WriteLine(employee); <span class="com">// Employee { FirstName = Jane, LastName = Doe, Position = Manager }</span></code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you implement &#8216;with&#8217; expressions in C# 9.0 records?</strong></h3>



<p class="custp1 p-mb-0">In C# 9.0, <strong>records</strong> provide a simple way to create immutable objects with value-based equality. The <span class="spanHT">with</span><strong> </strong>expression allows you to create a copy of an existing record object with some properties changed, while the original object remains unchanged.</p>



<button class="shbtn" id="shbtn36072" onclick="showHideBlock(36072)">&#9660; <u>Show example</u></button>
<div id="shdiv36072" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem;"><b>Defining a Record:</b></div>
<pre class="pchl"><code><span class="key">public</span> record Person(<span class="key">string</span> FirstName, <span class="key">string</span> LastName, <span class="key">int</span> Age); </code></pre>


<br>
<div style="padding-left: 0.3125rem;"><b>Creating an Instance of the Record:</b></div>
<pre class="pchl"><code><span class="key">var</span> originalPerson = <span class="key">new</span> Person(<span class="str">"John"</span>, <span class="str">"Doe"</span>, 30); </code></pre>


<br>
<div style="padding-left: 0.3125rem;"><b>Using the with Expression:</b></div>
<pre class="pchl"><code><span class="com">// create a new record based on an existing one with some modifications.</span>
<span class="key">var</span> updatedPerson = originalPerson <span class="key" style="background:#f2f19d;">with</span> { Age = 31 }; </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a &#8216;Record Struct</strong>&#8216; <strong>in C# 10.0?</strong></h3>



<p class="custp1 p-mb-0">Unlike regular records, which are reference types, a <span class="spanHT">record struct</span> is a value type. This means that it is stored on the stack and passed by value rather than by reference. By default, record structs are designed to be immutable. This makes them useful for defining small, lightweight data structures that should not change after creation.</p>



<pre class="pchl"><code><span class="key">public</span> <span class="key" style="background:#f2f19d;">record struct</span> Point(<span class="key">int</span> X, <span class="key">int</span> Y); </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a target-typed &#8216;new&#8217; expression in C# 9.0?</strong></h3>



<p class="custp1 p-mb-0">A target-typed <span class="spanHT">new</span> expression in C# 9.0 allows you to create an instance of an object without explicitly specifying the type when the type can be inferred from the context. This feature simplifies the syntax, making the code cleaner and more concise. The compiler infers the type of the object being created based on the context, so you don&#8217;t need to repeat the type on the right-hand side of the assignment.</p>



<pre class="pchl"><code><span class="key">List</span>&lt;<span class="key">int</span>&gt numbers = <span style="background:#f2f19d;"><span class="key">new</span>()</span>; <span class="com">// List&lt;int&gt; is inferred</span></code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the &#8216;init&#8217; accessor in C# 9.0?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">init</span> <strong>accessor</strong> in C# 9.0 is a new way to set properties during object initialization, making them immutable after the object is created. This means once an object is created, properties with <strong>init accessors</strong> cannot be modified afterward.</p>



<button class="shbtn" id="shbtn38736" onclick="showHideBlock(38736)">&#9660; <u>Show example</u></button>
<div id="shdiv38736" style="display: none;" class="shdt">

<br>
<div style="padding-left: 0.3125rem; color:red;"><b>Without init Accessor (Before C# 9.0):</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Person
{
    <span class="key">public</span> <span class="key">string</span> FirstName { get; set; }
    <span class="key">public</span> <span class="key">string</span> LastName { get; set; }
}

<span class="key">var</span> person = <span class="key">new</span> Person { FirstName = <span class="str">"John"</span>, LastName = <span class="str">"Doe"</span> };
<b>person.FirstName =</b> <span class="str">"Jane"</span>; <span class="com">// This is allowed, but changes the original object</span></code></pre>


<br><br>
<div style="padding-left: 0.3125rem;"><b>With init Accessor (C# 9.0 and Later):</b></div>
<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Person
{
    <span class="key">public</span> <span class="key">string</span> FirstName { get; <span style="background:#f2f19d;">init</span>; }
    <span class="key">public</span> <span class="key">string</span> LastName { get; init; }
}

<span class="key">var</span> person = <span class="key">new</span> Person { FirstName = <span class="str">"John"</span>, LastName = <span class="str">"Doe"</span> };
<b>person.FirstName =</b> <span class="str">"Jane"</span>; <span style="color:red;">// Error: Cannot modify because of <b>init</b></span></code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use the &#8216;range&#8217; and &#8216;index&#8217; operators</strong></h3>



<p class="custp1 p-mb-0">The <strong>range</strong> and <strong>index</strong> operators in C# are used to easily access specific elements or ranges of elements within arrays, strings, or other indexable collections. </p>



<p class="custp1 p-mb-0"><strong>1) Range Operator (..):</strong> The range operator (<span class="spanHT">..</span>) allows you to specify a range of elements. The syntax <span class="spanHT">start..end</span> extracts elements from the <span class="spanHT">start</span> index to the <span class="spanHT">end</span> index (exclusive). You can omit the start or end to take elements from the beginning or up to the end of the collection.</p>



<button class="shbtn" id="shbtn36051" onclick="showHideBlock(36051)">&#9660; <u>Show example</u></button>
<div id="shdiv36051" style="display: none;">

<pre class="pchl"><code><span class="key">int</span>[] numbers = { 10, 20, 30, 40, 50 };

<span class="com">// Extract elements from index 1 to 3 (20, 30, 40)</span>
<span class="key">int</span>[] middle = numbers[<span style="background:#f2f19d;">1..4</span>];

<span class="com">// Extract the first three elements (10, 20, 30)</span>
<span class="key">int</span>[] firstThree = numbers[<span style="background:#f2f19d;">..3</span>];

<span class="com">// Extract the last two elements (40, 50)</span>
<span class="key">int</span>[] lastTwo = numbers[<span style="background:#f2f19d;">^2..</span>]; </code></pre>

</div>
<br><br>



<p class="p-mb-0"><strong>2) Index Operator (^):</strong> The index operator <span class="spanHT">^</span> allows you to access elements from the end of a collection. The syntax <span class="spanHT">^n</span> refers to the element at the <span class="spanHT">n-th</span> position from the end.</p>



<button class="shbtn" id="shbtn38846" onclick="showHideBlock(38846)">&#9660; <u>Show example</u></button>
<div id="shdiv38846" style="display: none;">

<pre class="pchl"><code><span class="key">int</span>[] numbers = { 10, 20, 30, 40, 50 };

<span class="com">// Accesses the last element: 50</span>
<span class="key">int</span> lastElement = numbers[<span style="background:#f2f19d;">^1</span>];   

<span class="com">// Accesses the second-to-last element: 40</span>
<span class="key">int</span> secondLastElement = numbers[<span style="background:#f2f19d;">^2</span>]; </code></pre>

</div>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the &#8216;checked&#8217; and &#8216;unchecked&#8217; keywords in C#?</strong></h3>



<p class="custp1 p-mb-0">The <strong>checked</strong> and <strong>unchecked</strong> keywords in C# are used to control the behavior of arithmetic operations and conversions with respect to overflow. </p>



<p class="custp1 p-mb-0"><strong>1) &#8216;checked&#8217; Keyword:</strong> Enforces overflow checking and throws an exception if overflow occurs. Ensures data integrity by detecting overflows, particularly in critical calculations where overflow could lead to incorrect results. Often used in scenarios where arithmetic operations involve user input or data that could reach extreme values.</p>



<pre class="pchl"><code><span class="com">// This will throw an OverflowException</span>
<span class="key">int</span> result = <span class="key" style="background:#f2f19d;">checked</span>(max + 1); </code></pre>
<br>



<p class="p-mb-0"><strong>2) &#8216;unchecked&#8217; Keyword:</strong> Disables overflow checking, allowing arithmetic operations to wrap around without throwing an exception. Improves performance by avoiding the overhead of overflow checking.<br>Useful in scenarios where you are confident that overflow is either impossible or acceptable (e.g., when working with bitwise operations).</p>



<pre class="pchl"><code><span class="key">int</span> max = int.MaxValue;

<span class="com">// This will not throw an exception; it will wrap around</span>
<span class="key">int</span> result = <span class="key" style="background:#f2f19d;">unchecked</span>(max + 1); 

<span class="com">// Output: -2147483648 (wrapped around value)</span>
Console.WriteLine(result); </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the purpose of the &#8216;volatile&#8217; keyword in C#?</strong></h3>



<p class="custp1 p-mb-0">The <span class="spanHT">volatile</span> keyword in C# is used to indicate that a field may be modified by multiple threads simultaneously. It ensures that the most up-to-date value of the field is always read from memory, not from a CPU register or cache. Use the <span class="spanHT">volatile</span> keyword for fields that are shared between multiple threads and where simple atomic reads and writes (like int, bool, float, etc.) are required.</p>



<button class="shbtn" id="shbtn87453" onclick="showHideBlock(87453)">&#9660; <u>Show example</u></button>
<div id="shdiv87453" style="display: none;" class="shdt">

<pre class="pchl"><code><span class="key">public</span> <span class="key">class</span> Example
{
    <span class="key">private</span> <span class="key" style="background:#f2f19d;">volatile</span> <span class="key">bool</span> _isRunning;

    <span class="key">public</span> <span class="key">void</span> Start()
    {
        _isRunning = true;
        <span class="key">new</span> Thread(Run).Start();
    }

    <span class="key">public</span> <span class="key">void</span> Stop()
    {
        _isRunning = false;
    }

    <span class="key">private</span> <span class="key">void</span> Run()
    {
        <span class="key">while</span> (_isRunning)
        {
            <span class="com">// Perform work</span>
        }
    }
} </code></pre>

<br>
In this example, <strong>_isRunning</strong> is marked as <span class="spanHT">volatile</span> to ensure that the thread running the <strong>Run</strong> method always sees the latest value of <strong>_isRunning</strong> as set by the <strong>Stop</strong> method, even if <strong>Stop</strong> is called from another thread.

</div>
<br>



<p class="custp1 p-mb-0">It’s not suitable for more complex thread synchronization scenarios (like incrementing a value or checking and setting a value simultaneously); for those, you should use lock, Monitor, Mutex, etc.</p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How do you use &#8216;string interpolation&#8217; in C#?</strong></h3>



<p class="custp1 p-mb-0"><strong>String interpolation</strong> allows you to embed expressions directly within string literals, making it easier and more readable to format strings. Use the <span class="spanHT">$</span> symbol before the string and place expressions inside curly braces <span class="spanHT">{}</span> within the string.</p>



<pre class="pchl"><code><span class="key">string</span> name = <span class="str">"John"</span>;
<span class="key">int</span> age = 30;
<span class="key">string</span> message = <span style="background:#f2f19d;">$</span><span class="str">"My name is <span style="background:#f2f19d;">{name}</span> and I am <span style="background:#f2f19d;">{age}</span> years old."</span>; </code></pre>



<br><br><br><br>



<div id="download-questions" style="border: solid 1px lightblue; padding: 10px;">
<button class="shbtn" style="float: right; border-radius: 20px;" onclick="saveQuestionsAsPDF()">Download</button>
<div><span style="font-weight: bold; font-size: 20px; color: #7100e2;">Download all Questions as .PDF</span></div>
<div id="questions"><br><br><center><span style="color:#808080;"><i>loading&#8230;</i></span></center></div>
</div>



<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>



<style>
.shbtn {
    color: #fff;
    padding: 6px 12px;
    margin-top: 8px;
}
.shdt {
    box-shadow: lightblue 0px 1px 2px;
}
pre {
    margin-bottom: 0;
}
tbody>tr>th {
    font-weight: bold;
}
</style>

<script>
	function showHideBlock(val) {
		var btnx = document.getElementById("shbtn" + val);
		var divx = document.getElementById("shdiv" + val);

		if (divx.style.display === "none") {
			divx.style.display = "block";
			btnx.innerHTML = "&#9650; <u>Hide example</u>";
		} else {
			divx.style.display = "none";
			btnx.innerHTML = "&#9660; <u>Show example</u>";
		}
	}
</script>



<script>
window.onload = function (){
	var shbtnarr = document.getElementsByClassName("shbtn");
	var alreadySeen ={};
	console.log("shbtn count: " + shbtnarr.length);
	console.log("find duplicate - Start ---"); 
	for (element of shbtnarr) {
		if (alreadySeen[element.id]){
			console.log(element.id);
			alreadySeen[element.id] = false;
		}
		else {
			alreadySeen[element.id] = true;
		}
	}
	console.log("find duplicate - End ---"); 
	console.log()
	console.log("--- sh(alreadySeen) ids ---");
	console.log(alreadySeen);
	/* for (var key in alreadySeen)
	{
		console.log(key + " : " +  alreadySeen[key]);
	} */


	/*Sl.No for H3*/
	var h3arr = document.getElementsByClassName("hLBRed");
	var questions = document.getElementById("questions");
	questions.innerHTML = "<br><br><div><h2><center><b><u>C# Interview Questions</u></b></center></h2></div><br>";
	var count = 1;
	var searchResult = "";
	for (h3 of h3arr) {
/*if(count == 95){
debugger;
var test = h3.innerText.replace(/[^\w\s#?.,=<>]/gi, '');
}*/
		questions.innerHTML = questions.innerHTML + "<div>" + "<b>" + count + ")</b> " + h3.innerText.replace(/[^\w\s#?.,=<>']/gi, '').replace('<','&lt;').replace('>','&gt;') + "</div>";

		h3.innerHTML = "<b>" + count + ") " + h3.innerHTML + "</b>";
		h3.id = "q" + count;
		searchResult += '<div class="filter-list-item"><a href="#' + h3.id + '">' + h3.innerText + '</a></div>'
		count++;
	}

	document.getElementById('myList').innerHTML = searchResult;
};


/* Print Questions */
function saveQuestionsAsPDF(divId, title) { 
	if (document.getElementById("questions").innerText.trim().length == 0) return;

	var doc = new jsPDF();
	doc.fromHTML('<html><head></head><body><div>https://www.codeindotnet.com/all-interview-questions-and-answers/</div>' + document.getElementById("questions").innerHTML + '<br><br><br><div><b>See Other Questions &amp; Answers:</b> https://www.codeindotnet.com/all-interview-questions-and-answers/</div></body></html>');
	doc.save('csharp-interview-questons.pdf');
}

</script>



<script type="text/javascript">
        document.getElementById("myInput").addEventListener("keyup",
    		function searchFilter() {
    			// Declare variables
    			var input, filter, div, divs, a, i;
    			input = document.getElementById('myInput').value.replace(/\s{2,}/g, ' ').trim().toUpperCase();
				arrFilters = input.split(' ');
    			div = document.getElementById('myList');
    			divs = div.getElementsByClassName('filter-list-item');
				
    			if (document.getElementById("myList").style.display == "none"){
    				document.getElementById("myList").style.display = "block";
    			}

				if(input.length == 0){
					for (i = 0; i < divs.length; i++) {
						divs[i].style.display = '';						
					}
				}
				else {
					// Loop through all list items, and hide those who don't match the search query
					for (i = 0; i < divs.length; i++) {
						a = divs[i].getElementsByTagName('a')[0];
						divs[i].style.display = 'none';
						for (j = 0; j < arrFilters.length; j++) {
							if ((arrFilters[j].length > 0) && (a.innerHTML.toUpperCase().indexOf(arrFilters[j]) > -1)) {
								divs[i].style.display = '';
								break;
							} 						
						}
						
					}
				}
    
		});
    </script>



<script>
function displayAllResult(){
	document.getElementById("myInput").value = ''
	div = document.getElementById('myList');
	divs = div.getElementsByClassName('filter-list-item');
	for (i = 0; i < divs.length; i++) {
		divs[i].style.display = '';						
	}
}
</script>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/csharp-interview-questions-answers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>70+ Top SQL Interview Questions and Answers</title>
		<link>https://www.codeindotnet.com/sql-interview-questions-answers/</link>
					<comments>https://www.codeindotnet.com/sql-interview-questions-answers/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Fri, 19 Jul 2024 15:38:41 +0000</pubDate>
				<category><![CDATA[Interview Questions Answers]]></category>
		<category><![CDATA[SQL]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=7407</guid>

					<description><![CDATA[SQL Interview Questions Download all Questions as .PDF Search: Clear × What is a database? A database is an organized collection of structured data stored electronically. It allows for efficient storage, retrieval, and management of data. What is SQL? SQL, or Structured Query Language, is a programming language used to manage and interact with databases. [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br><br>



<h2 class="wp-block-heading has-text-align-center h2Cust1"><strong>SQL Interview Questions</strong></h2>



<p class="has-text-align-right"><strong><a href="#download-questions" data-type="internal" data-id="#download-questions">Download all Questions as .PDF</a></strong></p>



<div id="searchPopup">
	<div class="popup-header">			
		<span style="font-weight:bold;">Search: </span>
		<input type="text" id="myInput" autocomplete="off" placeholder=" type keyword(s) &amp; filter Questions..." onclick="document.getElementById('myList').style.display = 'block'; document.getElementById('btnpopclose').style.display = 'block';">
		<button onclick="displayAllResult();" style="padding: 5px 9px; border-radius: 10px; color:#fff;" >Clear</button>
		<button id="btnpopclose" class="popup-close" onclick="document.getElementById('myList').style.display = 'none'; document.getElementById('btnpopclose').style.display = 'none';">×</button>
	</div>
	<div id="myList"></div>		
</div>



<style>
.popup-close {
    font-size: 1.25rem;
    font-weight: 700;
    padding: .3125rem .625rem;
    border-radius: .3125rem;
    background-color: red;
    color: #fff;
    border: none;
    float: right;
    display: none;
    /*margin: -.3125rem;*/
}

#myInput{
/*width: 60%; */
width: calc(100% - 11.5625rem);
display:inline; 
border-radius: 10px; 
margin:0;
}
/*@media screen and (max-width: 750px) {
    #myInput {
        width: 46%;
    }
}*/

#searchPopup{
border: 1px solid #6a409759;
    padding: 10px;
    border-radius: 5px;
}

#myList{
line-height: 1.7; 
font-size: 16px; 
overflow-y: scroll; 
height: 250px; 
/*border-bottom: 3px lightgray solid;*/
display:none; 
margin-top: 15px;
}
</style>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a database?</strong></h3>



<p class="custp1">A <strong>database</strong> is an organized collection of structured data stored electronically. It allows for efficient storage, retrieval, and management of data.</p>



<br>



<h3 class="wp-block-heading hLBRed"><strong>What is SQL?</strong></h3>



<p class="p-mb-0 custp1">SQL, or Structured Query Language, is a programming language used to manage and interact with databases. It allows you to:</p>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li><strong>Retrieve Data</strong>: Get information from a database.</li>



<li><strong>Insert Data</strong>: Add new information to a database.</li>



<li><strong>Update Data</strong>: Change existing information in a database.</li>



<li><strong>Delete Data</strong>: Remove information from a database.</li>
</ol>



<p class="p-mb-0 custp1">In simple terms, SQL helps you work with data stored in a database.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is an SQL statement?</strong></h3>



<p class="custp1">An <strong>SQL statement</strong> ,also known as an SQL command, is used to interact with a database. It can perform various operations such as retrieving , updating , deleting data, or creating database objects like tables and indexes. Some examples of SQL statements are <span class="spanHT">SELECT</span>, <span class="spanHT">CREATE</span>, <span class="spanHT">DELETE</span>, <span class="spanHT">DROP</span>, <span class="spanHT">REVOKE</span>, and so on.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a schema?</strong></h3>



<p class="custp1 p-mb-0">A <strong>schema</strong> is a structure that defines the organization of data in a database. It includes tables, views, indexes, procedures, and other database objects, and helps organize and manage the data logically.</p>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>example:</u></i></b></div>



<pre class="pchl"><code><span class="com"><b>-- To view all schemas</b></span>
<span class="key">SELECT</span> * <span class="key">FROM</span> INFORMATION_SCHEMA.SCHEMATA;

<span class="com"><b>--To view the schema of a specific table</b></span>
<span class="key">SELECT</span> COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
<span class="key">FROM</span> INFORMATION_SCHEMA.COLUMNS
<span class="key">WHERE</span> TABLE_NAME = 'your_table_name'; </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a table and a field in SQL</strong></h3>



<p class="custp1 p-mb-0"><strong>Table</strong>: A table is a collection of related data organized in rows and columns within a database. Each row represents a record, and each column represents a field.</p>



<p><strong>Field</strong>: A field is a single column in a table, representing a specific piece of data within a record. It holds individual data values for each row in the table.</p>



<br>



<h3 class="wp-block-heading hLBRed"><strong><strong>How to create a Table?</strong></strong></h3>



<pre class="pchl"><code><span class="key">CREATE</span> <span class="key">TABLE</span> Employees (
    EmployeeID <span style="color:#FF33CC;">INT</span> <span class="key">IDENTITY</span>(1,1) <span class="key">PRIMARY KEY</span>,
    FirstName <span style="color:#FF33CC;">VARCHAR</span>(50) <span class="key">NOT</span> <span class="key">NULL</span>,
    LastName <span style="color:#FF33CC;">VARCHAR</span>(50) <span class="key">NOT</span> <span class="key">NULL</span>,
    BirthDate <span style="color:#FF33CC;">DATE</span>,
    HireDate <span style="color:#FF33CC;">DATE</span>,
    Salary <span style="color:#FF33CC;">DECIMAL</span>(10, 2)
); </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>How to add a column to a table?</strong></strong></h3>



<p class="custp1 p-mb-0">Use the <span class="spanHT">ALTER TABLE</span> statement with the <span class="spanHT">ADD</span> clause.</p>



<pre class="pchl"><code><span class="key">ALTER TABLE</span> table_name
<span class="key">ADD</span> new_column_name data_type; </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>How to rename a column of a table?</strong></strong></h3>



<pre class="pchl"><code><span class="key">ALTER</span> <span class="key">TABLE</span> table_name
<span class="key">RENAME</span> <span class="key">COLUMN</span> old_column_name TO new_column_name; </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>How to delete a column from a table?</strong></strong></h3>



<pre class="pchl"><code><span class="key">ALTER</span> <span class="key">TABLE</span> table_name
<span class="key">DROP</span> <span class="key">COLUMN</span> column_name; </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is an Alias?</strong></h3>



<p class="custp1 p-mb-0">An <strong>alias</strong> is a temporary name given to a table or column for the duration of a query. It helps make the query results more readable and can simplify complex queries.</p>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>example:</u></i></b></div>



<pre class="pchl"><code><b>-- Column Alias</b>
<span class="key">SELECT</span> column_name <span style="background:#f2f19d;"><span class="key"> AS</span> alias_name </span><span class="key">FROM</span> table_name;

<b>-- Table Alias</b>
<span class="key">SELECT</span> t.column1 <span class="key">FROM</span> table_name <span class="key">AS</span> <span style="background:#f2f19d;"> t </span>; </code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a Clause?</strong></h3>



<p class="custp1">A <strong>clause</strong> is a part of a SQL statement that specifies a condition or operation. Clauses define how to filter, sort, group, or join data within a query. Some examples are <span class="spanHT">WHERE</span>, <span class="spanHT">LIMIT</span>, <span class="spanHT">HAVING</span>, <span class="spanHT">LIKE</span>, <span class="spanHT">AND</span>, <span class="spanHT">OR</span>, <span class="spanHT">ORDER BY</span>, etc.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is DDL?</strong></h3>



<p class="custp1">Data Definition Language (DDL) is used to define and manage database structures. It includes commands like CREATE, ALTER, and DROP, which are used to create, modify, and delete database objects such as tables, indexes, and schemas.</p>



<br>



<h3 class="wp-block-heading hLBRed"><strong>What is DML?</strong></h3>



<p class="custp1">Data Manipulation Language (DML) is used to manage and manipulate data within database tables. It includes commands like SELECT, INSERT, UPDATE, and DELETE, which are used to retrieve, add, modify, and remove data.</p>



<br>



<h3 class="wp-block-heading hLBRed"><strong>What are the different types of SQL commands?</strong></h3>



<p class="custp1 p-mb-0"><strong>1) Data Definition Language (DDL)</strong>:</p>



<ul class="ol1 wp-block-list">
<li><strong>CREATE</strong>: Creates new database objects like tables, indexes, and views.</li>



<li><strong>ALTER</strong>: Modifies existing database objects.</li>



<li><strong>DROP</strong>: Deletes database objects.</li>



<li><strong>TRUNCATE</strong>: Removes all rows from a table, but the table structure remains.</li>
</ul>



<p class="p-mb-0"><strong>2) Data Manipulation Language (DML)</strong>:</p>



<ul class="ol1 wp-block-list">
<li><strong>SELECT</strong>: Retrieves data from the database.</li>



<li><strong>INSERT</strong>: Adds new rows of data to a table.</li>



<li><strong>UPDATE</strong>: Modifies existing data within a table.</li>



<li><strong>DELETE</strong>: Removes rows of data from a table.</li>
</ul>



<p class="p-mb-0"><strong>3) Data Control Language (DCL)</strong>:</p>



<ul class="ol1 wp-block-list">
<li><strong>GRANT</strong>: Gives users access privileges to the database.</li>



<li><strong>REVOKE</strong>: Removes access privileges from users.</li>
</ul>



<p class="p-mb-0"><strong>4) Transaction Control Language (TCL)</strong>:</p>



<ul class="ol1 wp-block-list">
<li><strong>COMMIT</strong>: Saves all changes made during the current transaction.</li>



<li><strong>ROLLBACK</strong>: Reverts changes made during the current transaction.</li>



<li><strong>SAVEPOINT</strong>: Sets a point within a transaction to which you can later roll back.</li>
</ul>



<p class="p-mb-0"><strong>5) Data Query Language (DQL)</strong>:</p>



<ul class="ol1 wp-block-list">
<li><strong>SELECT</strong>: Used to query and retrieve data from the database.</li>
</ul>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the different types of SQL relationships? Can you describe and give examples of each type?</strong></h3>



<br>



<p class="p-mb-0"><strong>1) One-to-One Relationship:</strong> Each row in &#8216;Table A&#8217; is linked to one and only one row in &#8216;Table B&#8217;, and vice versa.</p>



<p class="custp1 p-mb-0"><em><strong>example:</strong></em> A &#8216;Person&#8217; table with a &#8216;Passport&#8217; table where each person has one unique passport.</p>



<pre class="pchl"><code>Person (<span style="background:#f2f19d;">PersonID</span>, Name)
Passport (PassportID, <span style="background:#f2f19d;">PersonID</span>, PassportNumber) </code></pre><br>



<p class="p-mb-0"><strong>2) One-to-Many Relationship:</strong> A row in &#8216;Table A&#8217; can be associated with many rows in &#8216;Table B&#8217;, but a row in &#8216;Table B&#8217; is associated with only one row in &#8216;Table A&#8217;.</p>



<p class="custp1 p-mb-0"><strong><em>example: </em></strong>A &#8216;Customer&#8217; table with an &#8216;Orders&#8217; table where each customer can place multiple orders.</p>



<pre class="pchl"><code>Customer (<span style="background:#f2f19d;">CustomerID</span>, Name)
Orders (OrderID, <span style="background:#f2f19d;">CustomerID</span>, OrderDate) </code></pre><br>



<p class="p-mb-0"><strong>3) Many-to-One Relationship:</strong> (reverse of a one-to-many relationship) Many rows in &#8216;Table A&#8217; can be associated with one row in &#8216;Table B&#8217;.</p>



<p class="custp1 p-mb-0"><strong><em>example:</em></strong> Many employees belonging to one department.</p>



<pre class="pchl"><code>Department (<span style="background:#f2f19d;">DepartmentID</span>, DepartmentName)
Employee (EmployeeID, <span style="background:#f2f19d;">DepartmentID</span>, Name) </code></pre><br>



<p class="p-mb-0"><strong>4) Many-to-Many Relationship:</strong> Rows in &#8216;Table A&#8217; can be associated with many rows in &#8216;Table B&#8217; and vice versa.</p>



<p class="custp1 p-mb-0"><strong><em>example:</em></strong> A &#8216;Students&#8217; table and a &#8216;Courses&#8217; table where each student can enroll in multiple courses, and each course can have multiple students. Use a junction table to establish the relationship.</p>



<pre class="pchl"><code>Students (<span style="background:#f2f19d;">StudentID</span>, StudentName)
Courses (<span style="background:#f2f19d;">CourseID</span>, CourseName)
StudentCourses (<span style="background:#f2f19d;">StudentID, CourseID</span>) </code></pre>



<br><br><br>



<h2 class="wp-block-heading h2Cust1"><strong>Basic SQL Commands<strong> and Queries</strong></strong></h2>



<br>



<h3 class="wp-block-heading hLBRed"><strong>Basic SQL Commands and Queries.</strong></h3>



<pre class="pchl"><code><span class="com"><b>-- Select all columns from a table</b></span>
<span class="key">SELECT</span> <b>*</b> <span class="key">FROM</span> Employees

<span class="com"><b>-- Insert</b></span>
<span class="key">INSERT</span> <span class="key">INTO</span> Employees (EmployeeID, FirstName, LastName, BirthDate, HireDate, Salary)
<span class="key">VALUES</span> (1, 'John', 'Doe', '1980-01-01', '2020-06-15', 50000.00);

<span class="com"><b>-- Update</b></span>
<span class="key">UPDATE</span> Employees
<span class="key">SET</span> Salary = 55000.00
<span class="key">WHERE</span> EmployeeID = 1;

<span class="com"><b>-- Delete</b></span>
<span class="key">DELETE</span> <span class="key">FROM</span> Employees <span class="key">WHERE</span> EmployeeID = 1; 

<span class="com"><b>-- Get the Count of Rows in a Table</b></span>
<span class="key">SELECT</span> <span class="key"><b>COUNT</b></span>(*) <span class="key">FROM</span> Employees;

<span class="com"><b>--Sorting Records in a Table</b></span>
<span class="com">/* ASC specifies ascending order (default).*/</span>
<span class="com">/* DESC specifies descending order. */</span>

<span class="key">SELECT</span> * <span class="key">FROM</span> Employees <span class="key">ORDER BY</span> LastName <span class="key"><b>ASC</b></span>;
<span class="key">SELECT</span> * <span class="key">FROM</span> Employees <span class="key">ORDER BY</span> HireDate <span class="key"><b>DESC</b></span>;

<span class="com"><b>-- Selecting Distinct Records from a Single Table</b></span>
<span class="key">SELECT</span> <span class="key"><b>DISTINCT</b></span> LastName, FirstName <span class="key">FROM</span> Employees;

<span class="com"><b>-- Selecting Distinct Records from Two Tables</b></span>
<span class="key">SELECT</span> EmployeeID, FirstName, LastName <span class="key">FROM</span> Employees
<span class="key"><b>UNION</b></span>
<span class="key">SELECT</span> EmployeeID, FirstName, LastName <span class="key">FROM</span> FormerEmployees;

<span class="com"><b>-- Selecting Common Records from Two Tables</b></span>
<span class="key">SELECT</span> EmployeeID, FirstName, LastName <span class="key">FROM</span> Employees
<span class="key"><b>INTERSECT</b></span>
<span class="key">SELECT</span> EmployeeID, FirstName, LastName <span class="key">FROM</span> FormerEmployees; 
</code></pre>



<br><br><br>



<h2 class="wp-block-heading has-text-align-center h2Cust1" id="Intermediate-SQL-Interview-Questions"><strong>Intermediate SQL Interview Questions and Answers</strong></h2>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a Primary Key?</strong></h3>



<p class="custp1">A <strong>primary key</strong> is a column or a set of columns that uniquely identifies each row in a table. It ensures that no duplicate values or NULLs are present in the primary key column(s).</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Auto Increment?</strong></h3>



<p class="custp1 p-mb-0">Auto Increment is a feature that automatically generates a unique value for a specified column in a table for each new row inserted and is commonly used for primary key columns.</p>



<p class="custp1 p-mb-0"><span class="spanHT">IDENTITY(1,1)</span> is the keyword used to define an auto-increment column. <span class="spanHT">(1,1)</span> specifies the seed and increment values. The first <span class="spanHT">1</span> is the seed (starting value), and the second <span class="spanHT">1</span> is the increment (how much to increase for each new row).</p>



<pre class="pchl"><code><span class="key">CREATE</span> <span class="key">TABLE</span> TableName (
    ID <span class="key">INT</span> <span style="background:#f2f19d;"><span class="key">IDENTITY</span>(1,1)</SPAN> <span class="key">PRIMARY</span> <span class="key">KEY</span>,
); </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a foreign key?</strong></h3>



<p class="custp1">A <strong>foreign key</strong> is a column or a set of columns in one table that links to the primary key in another table. It is used to maintain referential integrity by ensuring that the value in the foreign key column matches a value in the referenced primary key column.</p>



<pre class="pchl"><code><span class="key">CREATE TABLE</span> Employees (
    EmployeeID <span class="key">INT PRIMARY KEY</span>,
    DepartmentID <span class="key">INT</span> <span style="background:#f2f19d;"><span class="key">FOREIGN KEY REFERENCES</span> Departments(DepartmentID)</span>
); </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Define a Unique Key in SQL</strong></h3>



<p class="custp1">A <strong>unique key</strong> is a column or a set of columns that ensures all values in that column or combination of columns are unique. It prevents duplicate values but allows one NULL value.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a constraint in SQL?</strong></h3>



<p class="custp1 p-mb-0">A <strong>constraint</strong> is a rule applied to a column or a set of columns in a table to enforce data integrity and ensure the accuracy and reliability of the data.</p>



<p class="custp1 p-mb-0"><em><strong><span style="text-decoration: underline;">Common constraints:</span></strong></em></p>



<ol class="ol1 wp-block-list">
<li><strong>Primary Key</strong>: Ensures each row in a table is unique and not NULL.</li>



<li><strong>Foreign Key</strong>: Ensures a column&#8217;s values match values in another table&#8217;s primary key.</li>



<li><strong>Unique</strong>: Ensures all values in a column are unique.</li>



<li><strong>Not Null</strong>: Ensures a column cannot have NULL values.</li>



<li><strong>Check</strong>: Ensures values in a column meet a specific condition.</li>
</ol>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Stored Procedure?</strong></h3>



<p class="custp1">A stored procedure is a named set of pre-written SQL commands/statements that is saved in a database in a compiled ready-to-use form and can be executed as a single unit. </p>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>Advantages::</u></i></b></div>



<ul class="ol1 wp-block-list">
<li>allows modular programming.</li>



<li>allows faster execution.</li>



<li>reduce the network traffic.</li>



<li>It can be used as a security mechanism.</li>
</ul>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>Types of Stored Procedures in SQL:</u></i></b></div>



<ol class="ol1 wp-block-list">
<li><strong>User-Defined Stored Procedures</strong>: Created by users to perform specific tasks or operations in a database.</li>



<li><strong>System Stored Procedures</strong>: Provided by the database system to perform administrative and system-level tasks.</li>



<li><strong>Temporary Stored Procedures</strong>: Stored in the tempdb database and used for temporary tasks, disappearing after the session ends.</li>



<li><strong>CLR Stored Procedures</strong>: Created using .NET languages and executed within the SQL Server Common Language Runtime (CLR).</li>
</ol>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a Subquery?</strong></h3>



<p class="custp1 p-mb-0">A <strong>subquery</strong> is a query nested inside another query. It is used to retrieve data that will be used in the main query as a condition to further restrict the data to be retrieved.</p>



<div><b><i><u>example:</u></i></b></div>



<pre class="pchl"><code><span class="key">SELECT</span> Name 
<span class="key">FROM</span> Employees 
<span class="key">WHERE</span> DeptID =<span style="background:#f2f19d;"> (<span class="key">SELECT</span> DeptID <span class="key">FROM</span> Departments <span class="key">WHERE</span> DeptName = 'Sales'); </span></code></pre>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a View?</strong></h3>



<p class="custp1">A view is a virtual table that shows data from base tables and other views (i.e., the outcome of a SELECT query), but not stored separately. It does not copy the memory space.</p>



<p class="p-mb-0">You should use a view in SQL when:</p>



<ol class="wp-block-list">
<li><strong>Simplifying Complex Queries</strong>: To encapsulate complex SQL queries into a single, reusable query.</li>



<li class="custp1"><strong>Enhancing Security</strong>: To restrict user access to specific rows or columns of data.</li>



<li class="custp1"><strong>Ensuring Data Consistency</strong>: To provide a consistent and unified presentation of data, even if the underlying table structure changes.</li>



<li class="custp1"><strong>Providing Data Abstraction</strong>: To present data in a different format or structure without modifying the original tables.</li>



<li class="custp1"><strong>Improving Readability and Maintenance</strong>: To make queries more readable and easier to maintain by breaking down complex logic into simpler, logical units.</li>
</ol>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can we create a view based on another view?</strong></h3>



<p class="custp1">Yes. This is also known as nested views.<br><strong><em>note:</em></strong> 1) it can affect performance, 2) the code becomes difficult to read and debug</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>Can we still use a view if the original table is deleted?</strong></h3>



<p class="custp1">No, you cannot use a view if the original table is deleted, because a view depends on the original table for its data. If the original table is deleted, the view loses its data source and becomes invalid.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Trigger?</strong></h3>



<p class="custp1">Triggers are a type of stored procedure that automatically run when data in a table or view is updated, inserted, or deleted. They are powerful tools used to enforce business rules whenever data changes.</p>



<p>A trigger can be executed either &#8216;before or after&#8217; an insert, update, or delete operation.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Cursors?</strong></h3>



<p class="custp1">Cursors allow row-by-row processing of the result sets. (or) A cursor in SQL is a database object used to retrieve, manipulate, and navigate through a result set row by row. It acts as a pointer to the rows of a query result.</p>



<p class="p-mb-0"><strong><em>Advantages of Cursors</em></strong></p>



<ol class="wp-block-list">
<li><strong>Row-by-Row Processing</strong>: Allows processing of individual rows, which is useful for complex row-by-row operations.</li>



<li class="custp1"><strong>Simplifies Complex Operations</strong>: Makes it easier to handle complex logic that can&#8217;t be achieved with set-based operations alone.</li>



<li class="custp1"><strong>Enhanced Control</strong>: Provides fine-grained control over query results and how they are processed.</li>
</ol>



<p class="p-mb-0"><strong><em>Disadvantages of Cursors</em></strong></p>



<ol class="wp-block-list">
<li><strong>Performance Overhead</strong>: Can be slower than set-based operations because they process each row individually.</li>



<li class="custp1"><strong>Resource Intensive</strong>: Consume more memory and resources, leading to potential scalability issues.</li>



<li class="custp1"><strong>Complexity</strong>: Can make code more complex and harder to maintain compared to set-based SQL operations.</li>
</ol>



<br>



<h3 class="wp-block-heading hLBRed"><strong>What are indexes? </strong></h3>



<p class="custp1"><strong>Indexes</strong> are special database objects that improve the speed of data retrieval. They act like pointers to quickly locate data within a table.</p>



<p class="p-mb-0"><strong><em>Types of Indexes:</em></strong></p>



<ol class="wp-block-list">
<li><strong>Clustered Index</strong>: Organizes the actual data rows in the table based on the index key. Only one per table.</li>



<li class="custp1"><strong>Nonclustered Index</strong>: Creates a separate structure pointing to the data rows. Multiple NonClustered indexes can exist per table.</li>



<li class="custp1"><strong>Unique Index</strong>: Ensures that all the values in the index key column are unique. It can be Clustered or NonClustered.</li>



<li class="custp1"><strong>Full-Text Index</strong>: Used for efficient searching of large text-based data. Supports full-text queries.</li>



<li class="custp1"><strong>Spatial Index</strong>: Used for indexing spatial data types like geometry or geography. Optimizes spatial queries.</li>



<li class="custp1"><strong>Filtered Index</strong>: NonClustered index with a WHERE clause. Indexes a subset of rows in a table.</li>



<li class="custp1"><strong>XML Index</strong>: Used for indexing XML data type columns. Optimizes XML data queries.</li>
</ol>



<p>Clustered and Non-clustered indexes are often used in real-time project.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is GROUP BY in SQL?</strong></h3>



<p class="custp1"><strong>GROUP BY</strong> is a clause used to group rows that have the same values in specified columns. It allows you to perform aggregate functions (like COUNT, SUM, AVG) on each group of rows.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the use of ORDER BY</strong>?</h3>



<p class="custp1 p-mb-0"><strong>ORDER BY</strong> is a clause used to sort the result set of a query by one or more columns, either in ascending (default) or descending order.</p>



<div><b><i><u>example:</u></i></b></div>



<p class="custp1"><span class="spanHT">SELECT * FROM products ORDER BY price DESC;</span></p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference between Primary key and Unique key?</strong></h3>



<br>



<ol class="wp-block-list">
<li><strong>Uniqueness</strong>: Both primary key and unique key ensure all values in the column are unique.</li>



<li class="custp1"><strong>Null Values</strong>: Primary key does not allow NULL values, while unique key allows one NULL value.</li>



<li class="custp1"><strong>Number of Keys Allowed</strong>: A table can have only one primary key but can have multiple unique keys.</li>



<li class="custp1"><strong>Index Creation</strong>: Primary key creates a clustered index by default (if supported), whereas unique key creates a non-clustered index by default.</li>



<li class="custp1"><strong>Purpose</strong>: Primary key uniquely identifies each record in a table, while unique key ensures the uniqueness of values in specific columns.</li>



<li class="custp1"><strong>Identification</strong>: Primary key is used to uniquely identify a row, while unique key is used to enforce uniqueness in columns.</li>
</ol>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>Define Candidate key, Alternate key and Composite key.</strong></h3>



<p class="custp1"><strong>Candidate Key</strong>: A candidate key is a column, or a set of columns, that can uniquely identify any record in a table. A table can have multiple candidate keys, but only one is chosen as the primary key.</p>



<p><strong>Alternate Key</strong>: An alternate key is any candidate key that is not chosen as the primary key. It is still capable of uniquely identifying records but serves as an alternative to the primary key.</p>



<p><strong>Composite Key</strong>: A composite key is a key that consists of two or more columns used together to uniquely identify a record. This is used when a single column is not sufficient to ensure uniqueness.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>Different between Delete and Truncate?</strong></h3>



<br>



<ol class="custp1 wp-block-list">
<li><strong>Operation Type</strong>: DELETE is a DML (Data Manipulation Language) command, while TRUNCATE is a DDL (Data Definition Language) command.</li>



<li class="custp1"><strong>Row-by-Row Deletion</strong>: DELETE can remove specific rows based on conditions, but TRUNCATE removes all rows from a table at once.</li>



<li class="custp1"><strong>WHERE Clause</strong>: DELETE allows the use of a WHERE clause (criteria) to filter rows, but TRUNCATE does not.</li>



<li class="custp1"><strong>Transaction Logging</strong>: DELETE logs each row deletion, making it slower, whereas TRUNCATE logs less (deallocation of data page), making it faster.</li>



<li class="custp1"><strong>Space Reclaiming</strong>: DELETE does not immediately free up space, but TRUNCATE does.</li>



<li class="custp1"><strong>Triggers Activation</strong>: DELETE activates triggers, but TRUNCATE does not.</li>



<li class="custp1"><strong>Foreign Key Constraints</strong>: DELETE can be used with foreign key constraints, but TRUNCATE cannot if foreign keys are present.</li>



<li class="custp1"><strong>Identity Reset</strong>: DELETE does not reset the identity column, while TRUNCATE does.</li>
</ol>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the On Delete cascade constraint?</strong></h3>



<br>



<p class="p-mb-0">The <span class="spanHT">ON DELETE CASCADE</span> constraint in SQL automatically deletes rows in a child table when the corresponding rows in the parent table are deleted.</p>



<pre class="pchl"><code><span class="com"><b>/* -- Child Table -- */</b></span>
<span class="key">CREATE TABLE</span> Employees (
    EmployeeID <span class="key">INT PRIMARY KEY</span>,
    DepartmentID <span class="key">INT</span>,
    <span class="key">FOREIGN KEY</span> (DepartmentID) <span class="key">REFERENCES</span> Departments(DepartmentID) <span class="key" style="background:#f2f19d;">ON DELETE CASCADE</span>
); </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is join in SQL</strong>? <strong>What are the different types of joins? What is the difference between them?</strong></h3>



<p class="custp1"><strong>Joins</strong> are used to combine rows from two or more tables based on a related column between them. There are different types of joins &#8211; Inner Join, Left Join, Right Join, Full Join, Cross Join and Sefl Join.</p>



<p class="p-mb-0"><strong><em>Types of Joins and differences:</em></strong></p>



<ol class="wp-block-list">
<li><strong>Inner Join &#8211;</strong> Returns rows with matching values in both tables. <br><span class="spanHT">SELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.id</span></li>



<li class="custp1"><strong>Left Join (or Left Outer Join) &#8211;</strong> Returns all rows from the left table and matching rows from the right table. If no match, returns NULLs for the right table. <br><span class="spanHT">SELECT * FROM table1 <b>LEFT JOIN</b> table2 ON table1.id = table2.id</span></li>



<li class="custp1"><strong>Right Join (or Right Outer Join) &#8211; </strong>Returns all rows from the right table and matching rows from the left table. If no match, returns NULLs for the left table. <br><span class="spanHT">SELECT * FROM table1 <b>RIGHT JOIN</b> table2 ON table1.id = table2.id</span></li>



<li class="custp1"><strong>Full Join (or Full Outer Join) &#8211;</strong> Returns rows when there is a match in one of the tables. If no match, returns NULLs for non-matching rows from both tables. <br><span class="spanHT">SELECT * FROM table1 <b>FULL JOIN</b> table2 ON table1.id = table2.id</span></li>



<li class="custp1"><strong>Cross Join &#8211;</strong> Returns the Cartesian product of both tables, meaning all possible combinations of rows <br><span class="spanHT">SELECT * FROM table1 <b>CROSS JOIN</b> table2</span></li>



<li class="custp1"><strong>Self Join &#8211;</strong> Joins a table to itself <br><span class="spanHT">SELECT a.<em>, b.</em> FROM table a, table b WHERE a.id = b.ref_id</span></li>
</ol>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Clustered and Non-clustered Indexes?</strong></h3>



<p class="custp1 p-mb-0"><strong>Clustered Index:</strong> A clustered index organizes the actual data rows in a table based on the index key. It&#8217;s like sorting a book by its chapters; there&#8217;s only one way to arrange the pages. A table can have only one clustered index.</p>



<p class="custp1"><strong>Nonclustered Index:</strong> A nonclustered index creates a separate structure that points to the data rows, like an index at the back of a book pointing to pages. It does not change the order of the actual data. A table can have multiple nonclustered indexes.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between Clustered and Non-clustered indexes?</strong></h3>



<br>



<table>
    <thead>
        <tr>
            <th></th>
            <th>Clustered Index</th>
            <th>Nonclustered Index</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th><b>Storage</b></th>
            <td>Stores the actual data rows in the order of the index key</td>
            <td>Stores a separate structure pointing to the data rows</td>
        </tr>
        <tr>
            <th><b>Table Limit</b></th>
            <td>Only one clustered index per table</td>
            <td>Multiple nonclustered indexes per table</td>
        </tr>
        <tr>
            <th><b>Data Access Speed</b></th>
            <td>Generally faster for retrievals that use the index</td>
            <td>Slightly slower than clustered indexes for data retrieval</td>
        </tr>
        <tr>
            <th><b>Physical Order</b></th>
            <td>Reorders the physical data in the table</td>
            <td>Does not affect the physical order of data</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?</strong></h3>



<p class="custp1">You can use Having Clause with the GROUP BY function in a query and WHERE Clause is applied to each row before, they are part of the GROUP BY function in a query.</p>



<table>
    <thead>
        <tr>
            <th>WHERE Clause</th>
            <th>HAVING Clause</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Filters rows before grouping</td>
            <td>Filters groups after grouping</td>
        </tr>
        <tr>
            <td>Cannot be used with aggregate functions</td>
            <td>Can be used with aggregate functions</td>
        </tr>
        <tr>
            <td>Applied to individual rows</td>
            <td>Applied to groups of rows</td>
        </tr>
        <tr>
            <td>SELECT * FROM table WHERE condition;</td>
            <td>SELECT column, COUNT(*) FROM table GROUP BY column HAVING condition;</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between BETWEEN and IN operators?</strong></h3>



<br>



<p class="p-mb-0"><strong>1) BETWEEN operator:</strong> To filter the results within a specified range.</p>



<pre class="pchl"><code><span class="key">SELECT</span> * <span class="key">FROM</span> Employees
<span class="key">WHERE</span> Salary <span style="background:#f2f19d;"><span class="key">BETWEEN</span> 30000 <span class="key">AND</span> 50000</span>; </code></pre>



<p class="custp1 p-mb-0"><strong>2) IN operator:</strong> To filter the results based on a specified set of values.</p>



<pre class="pchl"><code><span class="key">SELECT</span> * <span class="key">FROM</span> Employees
<span class="key">WHERE</span> DepartmentID <span style="background:#f2f19d;"><span class="key">IN</span> (1, 4, 8)</span>; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between UNION and UNION ALL SQL syntax?</strong></h3>



<p class="custp1">UNION syntax is used to select information from two or more tables. But it selects only distinct records from tables, while UNION ALL selects all records from tables.<br><strong><em>Note:</em> </strong>Selected records should have the same datatype else the syntax will not work.</p>



<table>
    <thead>
        <tr>
            <th>UNION</th>
            <th>UNION ALL</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Removes duplicate rows</td>
            <td>Includes all duplicate rows</td>
        </tr>
        <tr>
            <td>Slower due to duplicate removal</td>
            <td>Faster as it does not remove duplicates</td>
        </tr>
        <tr>
            <td>Use when you need a distinct set of rows</td>
            <td>Use when you need all rows, including duplicates</td>
        </tr>
        <tr>
            <td>SELECT * FROM table1 <br><b>UNION</b><br> SELECT * FROM table2;</td>
            <td>SELECT * FROM table1 <br><b>UNION ALL</b><br> SELECT * FROM table2;</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Different between UNION and Joins</strong></h3>



<br>



<table>
    <thead>
        <tr>
            <th>UNION</th>
            <th>Joins</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Combines results from two or more queries</td>
            <td>Combines columns from two or more tables based on a related column</td>
        </tr>
        <tr>
            <td>Stacks results vertically (adds rows)</td>
            <td>Merges results horizontally (adds columns)</td>
        </tr>
        <tr>
            <td>Removes duplicates (UNION) or includes all (UNION ALL)</td>
            <td>Keeps all matching rows</td>
        </tr>
        <tr>
            <td>Used when you have similar data in different tables that you want to combine</td>
            <td>Used when you need to retrieve related data from multiple tables</td>
        </tr>
        <tr>
            <td>SELECT column1 FROM table1 <br><b>UNION</b><br> SELECT column1 FROM table2;</td>
            <td>SELECT table1.column1, table2.column2 FROM table1 <br><b>JOIN</b><br> table2 ON table1.id = table2.id;</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What do you mean by a NULL value in SQL?</strong></h3>



<p class="custp1">A <strong>NULL value</strong> represents missing or unknown data. It is different from zero, an empty string, or any other value. NULL indicates the absence of data in a column that the value for a particular column is not known or does not exist.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the difference between COALESCE() &amp; ISNULL()?</strong></h3>



<br>



<table>
    <thead>
        <tr>
            <th>COALESCE()</th>
            <th>ISNULL()</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Returns the first non-null value from a list</td>
            <td>Replaces null with a specified value</td>
        </tr>
        <tr>
            <td>COALESCE(expression1, expression2, &#8230;, expressionN)</td>
            <td>ISNULL(expression, replacement_value)</td>
        </tr>
        <tr>
            <td>Multiple arguments</td>
            <td>Two arguments only</td>
        </tr>
        <tr>
            <td>Standard SQL</td>
            <td>Specific to SQL Server</td>
        </tr>
        <tr>
            <td>Useful when checking multiple columns or expressions</td>
            <td>Simple null replacement with one value</td>
        </tr>
        <tr>
            <td><pre class="pchl"><code><span class="key">SELECT</span> <span style="color:#FF33CC;"><b>COALESCE</b></span>(FirstName, LastName, &#39;NoName&#39;) <span class="key">AS</span> Name</code></pre></td>
            <td><pre class="pchl"><code><span class="key">SELECT</span> <span style="color:#FF33CC;"><b>ISNULL</b></span>(FirstName, &#39;NoName&#39;) <span class="key">AS</span> Name</code></pre></td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are the different types of SQL operators?</strong></h3>



<br>



<ul class="ol1 wp-block-list">
<li>Arithmetic (<span class="spanHT">+</span>, <span class="spanHT">&#8211;</span>, <span class="spanHT">*</span>, <span class="spanHT">/</span>, etc.)</li>



<li>Comparison (<span class="spanHT">&gt;</span>, <span class="spanHT">&lt;</span>, <span class="spanHT">=</span>, <span class="spanHT">&gt;=</span>, etc.)</li>



<li>Compound (<span class="spanHT">+=</span>, <span class="spanHT">-=</span>, <span class="spanHT">*=</span>, <span class="spanHT">/=</span>, etc.)</li>



<li>Logical (<span class="spanHT">AND</span>, <span class="spanHT">OR</span>, <span class="spanHT">NOT</span>, <span class="spanHT">BETWEEN</span>, etc.)</li>



<li>String (<span class="spanHT">%</span>, <span class="spanHT">_</span>, <span class="spanHT">+</span>, <span class="spanHT">^</span>, etc.)</li>



<li>Set (<span class="spanHT">UNION</span>, <span class="spanHT">UNION ALL</span>, <span class="spanHT">INTERSECT</span>, and <span class="spanHT">MINUS</span> (or <span class="spanHT">EXCEPT</span>))</li>
</ul>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>What operator is used in the query for pattern (word/text) matching?</strong></strong></h3>



<p class="custp1">The&nbsp;<span class="spanHT">LIKE</span>&nbsp;operator in combination with the&nbsp;<span class="spanHT">%</span>&nbsp;and&nbsp;<span class="spanHT">_</span>&nbsp;wildcards. The&nbsp;<span class="spanHT">%</span>&nbsp;wildcard represents any number of characters including zero, while&nbsp;<span class="spanHT">_</span>&nbsp;– strictly one character.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is the correct order of statements in a SELECT query?</strong></h3>



<br>



<p><span class="spanHT">SELECT</span>&nbsp;–&gt;&nbsp;<span class="spanHT">FROM</span>&nbsp;–&gt;&nbsp;<span class="spanHT">JOIN</span>&nbsp;–&gt;&nbsp;<span class="spanHT">ON</span>&nbsp;–&gt;&nbsp;<span class="spanHT">WHERE</span>&nbsp;–&gt;&nbsp;<span class="spanHT">GROUP BY</span>&nbsp;–&gt;&nbsp;<span class="spanHT">HAVING</span>&nbsp;–&gt;&nbsp;<span class="spanHT">ORDER BY</span>&nbsp;–&gt;&nbsp;<span class="spanHT">LIMIT</span></p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>In what order does the interpreter execute the statements in a SELECT query?</strong></h3>



<br>



<p><span class="spanHT">FROM</span>&nbsp;–&gt;&nbsp;<span class="spanHT">JOIN</span>&nbsp;–&gt;&nbsp;<span class="spanHT">ON</span>&nbsp;–&gt;&nbsp;<span class="spanHT">WHERE</span>&nbsp;–&gt;&nbsp;<span class="spanHT">GROUP BY</span>&nbsp;–&gt;&nbsp;<span class="spanHT">HAVING</span>&nbsp;–&gt;&nbsp;<span class="spanHT">SELECT</span>&nbsp;–&gt;&nbsp;<span class="spanHT">ORDER BY</span>&nbsp;–&gt;&nbsp;<span class="spanHT">LIMIT</span></p>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a Function in SQL.</strong></h3>



<p class="custp1 p-mb-0">A <strong>function</strong> is a reusable set of SQL statements that perform a specific task and return a single value. Functions can take input parameters and are often used to encapsulate logic that can be applied to data within queries.</p>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><u>Examples of Functions</u></b></div>



<p class="custp1 p-mb-0"><strong>1) Built-in Functions:</strong> SUM(), AVG(), COUNT(), MAX(), MIN()</p>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>example:</u></i></b></div>



<pre class="pchl"><code><span class="key">SELECT</span> <span class="key"><b>SUM</b></span>(Amount) <span class="key">AS</span> TotalSales <span class="key">FROM</span> Sales; </code></pre><br>



<p class="custp1 p-mb-0"><strong>2) User-defined Functions:</strong> Functions created by users to perform custom operations.</p>



<p class="custp1 p-mb-0"><strong><em><span style="text-decoration: underline;">Syntax:</span></em></strong></p>



<pre class="pchl"><code><span class="key">CREATE</span> <span class="key">FUNCTION</span> dbo.Square(@Number <span class="key">INT</span>)
<span class="key">RETURNS INT</span>
<span class="key">AS</span>
<span class="key">BEGIN</span>
    <span class="key">RETURN</span> @Number * @Number;
<span class="key">END</span>; </code></pre>



<p class="custp1 p-mb-0"><strong><em><span style="text-decoration: underline;">Usage:</span></em></strong></p>



<pre class="pchl"><code><span class="key">SELECT</span> <b>dbo.Square(4)</b> <span class="key">AS</span> SquareOfFour;  <span class="com">-- Returns 16</span> </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Pre-defined function in SQL?</strong></h3>



<p class="custp1 p-mb-0">A <strong>pre-defined function</strong> in SQL is a built-in function provided by the database system that performs a specific operation. These functions are ready to use and do not require user-defined code.</p>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>pre-defined functions:</u></i></b></div>



<ul class="ol1 wp-block-list">
<li><strong>Aggregate Functions</strong>: SUM(), AVG(), COUNT()</li>



<li><strong>String Functions</strong>: CONCAT(), UPPER(), LOWER()</li>



<li><strong>Date Functions</strong>: NOW(), DATEADD(), DATEDIFF()</li>



<li><strong>Numeric Functions</strong>: ROUND(), ABS(), SQRT()</li>
</ul>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What are Aggregate functions? name a few.</strong></h3>



<p class="custp1 p-mb-0"><strong>Aggregate functions</strong> in SQL perform calculations on multiple rows of a table and return a single value.</p>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>aggregate functions:</u></i></b></div>



<ol class="ol1 custp1 wp-block-list">
<li><strong>COUNT</strong>: Returns the number of rows.</li>



<li><strong>SUM</strong>: Returns the total sum of a numeric column.</li>



<li><strong>AVG</strong>: Returns the average value of a numeric column.</li>



<li><strong>MAX</strong>: Returns the highest value in a column.</li>



<li><strong>MIN</strong>: Returns the lowest value in a column.</li>
</ol>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is Window Function in SQL?</strong></h3>



<p class="custp1 p-mb-0">A <strong>window function</strong> performs calculations across a set of table rows related to the current row. Unlike aggregate functions, it doesn&#8217;t group rows into a single output but provides a result for each row, maintaining the individual row identities.</p>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>window functions:</u></i></b></div>



<ul class="ol1 wp-block-list">
<li><strong>ROW_NUMBER()</strong>: Assigns a unique number to each row within a partition.</li>



<li><strong>RANK()</strong>: Assigns a rank to each row within a partition, allowing for ties.</li>



<li><strong>SUM()</strong>: Calculates a running total for a column within a partition.</li>
</ul>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What Scalar Functions</strong>? <strong>Can you name a few examples?</strong></h3>



<p class="custp1 p-mb-0">Scalar function operate on a single value and return a single value. It can be used in the <span class="spanHT">SELECT</span> statement, <span class="spanHT">WHERE</span> clause, or anywhere an expression is allowed. </p>



<p class="custp1">Some example are &#8211; <span class="spanHT">LENGTH()</span>, <span class="spanHT">UPPER()</span>, <span class="spanHT">LOWER()</span>, <span class="spanHT">INITCAP()</span>, <span class="spanHT">SUBSTR()</span>, <span class="spanHT">ROUND()</span>, <span class="spanHT">NOW()</span>, <span class="spanHT">CAST()</span>, <span class="spanHT">CONVERT()</span>.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>What is the&nbsp;CASE()&nbsp;function?</strong></strong></h3>



<p class="custp1">The CASE function allows you to perform conditional logic in your queries. It returns different values based on specified conditions.</p>



<pre class="pchl"><code><span class="key">SELECT</span> 
    <span class="key">CASE</span>
        <span class="key">WHEN</span> Salary &gt 50000 <span class="key">THEN</span> 'High'
        <span class="key">WHEN</span> Salary &gt 30000 <span class="key">THEN</span> 'Medium'
        <span class="key">ELSE</span> 'Low'
    <span class="key">END AS</span> SalaryLevel
<span class="key">FROM</span> Employees; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a temporary table in SQL, and what are the different types of temporary tables?</strong></h3>



<p class="custp1 p-mb-0">A temporary table is a short-lived table used to store data temporarily during a session or for intermediate results in a query.</p>



<p class="custp1 p-mb-0"><strong><span style="text-decoration: underline;">Two types of Temporary Tables:</span></strong></p>



<ul class="ol1 wp-block-list">
<li><strong>Local Temporary Table</strong>: Prefixed with <span class="spanHT">#</span>, limited to the current session.</li>



<li><strong>Global Temporary Table</strong>: Prefixed with <span class="spanHT">##</span>, available to all sessions until the last session ends.</li>
</ul>



<p class="custp1 p-mb-0"><strong><span style="text-decoration: underline;">Usage:</span></strong></p>



<p class="custp1 p-mb-0"><strong><em>Method 1:</em></strong> To insert data into a temporary table <em>without explicitly creating the table structure</em>, you can use the <span class="spanHT">SELECT</span> <span class="spanHT">INTO</span> statement. This statement creates the temporary table and inserts the data in a single step.</p>



<pre class="pchl"><code><span class="key">SELECT</span> EmployeeID, FirstName, LastName
<span style="background:#f2f19d;"><span class="key">INTO</span> #TempTable</span>
<span class="key">FROM</span> Employees
<span class="key">WHERE</span> DepartmentID = 1; </code></pre>
<br>



<p class="custp1 p-mb-0"><strong><em>Method 2:</em></strong> Create a temporary table and then insert data implicitly.</p>



<pre class="pchl"><code><span class="key">CREATE TABLE</span> <span style="background:#f2f19d;">#TempTable</span> (
    Column1 <span class="key">INT</span>,
    Column2 NVARCHAR(50)
); 

<span class="com">-- Verify the data in the temporary table</span>
<span class="key">SELECT</span> * <span class="key">FROM</span> #TempEmployees;</code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a Table Variable?</strong></h3>



<p class="custp1 p-mb-0">A table variable is a type of variable used to store temporary data in a structured format, similar to a table, within the scope of a batch, stored procedure, or function. <span class="spanHT">@</span> is used for declaring Table variables. </p>



<pre class="pchl"><code><span class="com">/* Creating a Table Variable */</span>
<span class="key">DECLARE</span> <span style="background:#f2f19d;">@TempTable</span> <span class="key">TABLE</span> (
    Column1 <span class="key">INT</span>,
    Column2 <span class="key">NVARCHAR</span>(50)
);

<span class="com">/* Insert data into the table variable */</span>
<span class="com">-- Method 1: Implicit Insertion</span>
<span style="background:#f2f19d;"><span class="key">INSERT INTO</span> @TempTable</span> (Column1, Column2)
<span class="key">VALUES</span> (1, 'Sample'), (2, 'Example');

<span class="com">-- Method 2: Explicit Insertion</span> 
<span style="background:#f2f19d;"><span class="key">INSERT INTO</span> @TempTable</span>(Column1, Column2)
<span class="key" style="background:#f2f19d;">SELECT</span> Column1, Column2 <span class="key">FROM</span> ExistingTable <span class="key">WHERE</span> SomeCondition;


<span class="com">/* Select data from the table variable */</span>
<span class="key">SELECT</span> * <span class="key">FROM</span> @TempTable; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>Difference Between Temporary Table and Table Variable.</strong></h3>



<br>
<table>
    <thead>
        <tr>
            <th></th>
            <th>Temporary Table</th>
            <th>Table Variable</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th><b>Creation Syntax</b></th>
            <td>CREATE TABLE #TempTable</td>
            <td>DECLARE @TableVariable TABLE</td>
        </tr>
        <tr>
            <th><b>Scope</b></th>
            <td>Session or connection</td>
            <td>Batch, stored procedure, or function</td>
        </tr>
        <tr>
            <th><b>Prefix Used</b></th>
            <td># for local, ## for global</td>
            <td>@</td>
        </tr>
        <tr>
            <th><b>Transaction Support</b></th>
            <td>Fully supported</td>
            <td>Limited</td>
        </tr>
        <tr>
            <th><b>Performance</b></th>
            <td>Better for larger datasets</td>
            <td>Better for smaller datasets</td>
        </tr>
        <tr>
            <th><b>Index Creation</b></th>
            <td>Can create indexes</td>
            <td>Cannot create indexes explicitly</td>
        </tr>
        <tr>
            <th><b>Storage Location</b></th>
            <td>Uses TempDB</td>
            <td>Uses memory</td>
        </tr>
        <tr>
            <th><b>Lifetime</b></th>
            <td>Exists until session ends</td>
            <td>Exists until batch or procedure ends</td>
        </tr>
    </tbody>
</table>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is CTE</strong> (<strong>Common Table Expression</strong>)?</h3>



<p class="custp1">A <strong>CTE (Common Table Expression)</strong> is a temporary result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. It makes complex queries easier to read and manage by breaking them into simpler parts. CTEs are defined using the <span class="spanHT">WITH</span> keyword.</p>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>example:</u></i></b></div>



<pre class="pchl"><code><span class="key">WITH</span> SalesCTE <span class="key">AS</span> (
    <span class="com">-- CTE query</span>
    <span class="key">SELECT</span> SalesPerson, <span class="key">SUM</span>(SalesAmount) <span class="key">AS</span> TotalSales
    <span class="key">FROM</span> Sales
    <span class="key">GROUP</span> <span class="key">BY</span> SalesPerson
)
<span class="com">-- Main query using the CTE</span>
<span class="key">SELECT</span> SalesPerson, TotalSales
<span class="key">FROM</span> SalesCTE
<span class="key">WHERE</span> TotalSales &gt 10000; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is MERGE in SQL? Give a basic example.</strong></h3>



<p class="custp1 p-mb-0"><strong>MERGE</strong> is a statement that allows you to perform INSERT, UPDATE, and DELETE operations in a single statement. It is used to synchronize two tables by merging them based on a specified condition.</p>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>example:</u></i></b></div>



<pre class="pchl"><code><span class="key">MERGE</span> <span class="key">INTO</span> Employees <span class="key">AS</span> target
<span class="key">USING</span> NewEmployees <span class="key">AS</span> source
<span class="key">ON</span> target.EmployeeID = source.EmployeeID
<span class="key">WHEN</span> <span class="key">MATCHED</span> <span class="key">THEN</span>
    <span class="key">UPDATE</span> <span class="key">SET</span> target.Name = source.Name, target.Salary = source.Salary
<span class="key">WHEN</span> <span class="key">NOT</span> <span class="key">MATCHED</span> <span class="key">BY</span> <span class="key">TARGET</span> <span class="key">THEN</span>
    <span class="key">INSERT</span> (EmployeeID, Name, Salary) <span class="key">VALUES</span> (source.EmployeeID, source.Name, source.Salary)
<span class="key">WHEN</span> <span class="key">NOT</span> <span class="key">MATCHED</span> <span class="key">BY</span> <span class="key">SOURCE</span> <span class="key">THEN</span>
    <span class="key">DELETE</span>; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is normalization? What are the different types of normalization?</strong></h3>



<p class="custp1"><strong>Normalization</strong> is the process of organizing a database to reduce redundancy and improve data integrity. It involves dividing large tables into smaller, related tables and defining relationships between them. Normalization helps maintain data accuracy and efficiency in a database.</p>



<p class="p-mb-0"><strong><em>Types of Normalization:</em></strong></p>



<ol class="wp-block-list">
<li><strong>First Normal Form (1NF)</strong>: Ensures each column contains only atomic (indivisible) values and each entry in a column is of the same type.</li>



<li class="custp1"><strong>Second Normal Form (2NF)</strong>: Meets all the requirements of 1NF and ensures that all non-key columns are fully dependent on the primary key.</li>



<li class="custp1"><strong>Third Normal Form (3NF)</strong>: Meets all the requirements of 2NF and ensures that all columns are directly dependent on the primary key, eliminating transitive dependencies.</li>



<li class="custp1"><strong>Boyce-Codd Normal Form (BCNF)</strong>: A stricter version of 3NF where every determinant is a candidate key.</li>



<li class="custp1"><strong>Fourth Normal Form (4NF)</strong>: Meets all the requirements of BCNF and ensures that multi-valued dependencies are eliminated.</li>



<li class="custp1"><strong>Fifth Normal Form (5NF)</strong>: Ensures that any remaining anomalies are eliminated, usually dealing with join dependencies.</li>
</ol>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is denormalization?</strong></h3>



<p class="custp1"><strong>Denormalization</strong> is the process of combining tables to reduce the number of joins needed for queries. This can improve read performance by storing redundant data, making data retrieval faster and simpler. However, it may lead to increased storage requirements and potential data inconsistencies.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>How can you raise custom errors from stored procedure?</strong></h3>



<br>



<p>The <span class="spanHT">RAISERROR</span> statement is used to raise custom errors from a stored procedure.</p>



<div><b><i><u>syntax:</u></i></b></div>



<pre class="pchl"><code>RAISERROR ('error message', 10, 1);</code></pre>



<p class="custp1 p-mb-0">It accepts three parameters:</p>



<ol class="ol1 wp-block-list">
<li><strong>Error Message:</strong> Custom text message </li>



<li><strong>Error Severity:</strong> Severity levels from 11 to 19 can be used for user-defined errors</li>



<li><strong>Error State:</strong> State is an integer from 0 to 255</li>
</ol>



<div><b><i><u>example:</u></i></b></div>



<pre class="pchl"><code><span class="key">ALTER</span> <span class="key">PROCEDURE</span> AddCustomer
	@Column2 <span class="key">int</span> =NULL
<span class="key">AS</span>

<span class="key">DECLARE</span> @ErrorMsgID <span class="key">int</span>

<span class="key">INSERT</span> Customer <span class="key">VALUES</span> (@Column2)
	
<span class="key">SET</span> @ErrorMsgID = <span style="background:#f2f19d;"><b> @@ERROR </b></span>
	
<span class="key">IF</span> @ErrorMsgID &lt;&gt 0
<span class="key">BEGIN</span>
	<span style="background:#f2f19d;"><span class="key"><b> RAISERROR</b></span> (<span class="com">'An error occured updating the Customer table'</span>, 10, 1) </span>
<span class="key">END</span> </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a Transaction in SQL?</strong></h3>



<p class="custp1 p-mb-0">A <strong>transaction</strong> is a sequence of one or more SQL operations treated as a single unit of work. All operations within a transaction must be completed successfully; otherwise, none of them are applied to the database.</p>



<p class="custp1 p-mb-0"><strong>Purpose &#8211;</strong> ensure data integrity and consistency. It follows the ACID properties (Atomicity, Consistency, Isolation, Durability)</p>



<p class="custp1 p-mb-0"><strong>When to Use &#8211; </strong>Use transactions when you need to ensure that a series of operations are completed successfully together. Common scenarios include:</p>



<ul class="ol1 wp-block-list">
<li>Transferring funds between accounts.</li>



<li>Inserting related data into multiple tables.</li>



<li>Updating multiple records in a dependent manner.</li>
</ul>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>example:</u></i></b></div>



<pre class="pchl"><code><span class="key">BEGIN</span> TRANSACTION;

<span class="key">UPDATE</span> Accounts
<span class="key">SET</span> Balance = Balance - 100
<span class="key">WHERE</span> AccountID = 1;

<span class="key">UPDATE</span> Accounts
<span class="key">SET</span> Balance = Balance + 100
<span class="key">WHERE</span> AccountID = 2;

<span class="key">IF</span> <span style="color:#FF33CC;">@@ERROR</span> = 0
    COMMIT;
<span class="key">ELSE</span>
    <span class="key">ROLLBACK</span>; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is a Pivot Table? Give basic example</strong></h3>



<p class="custp1 p-mb-0">A <strong>pivot table</strong> in SQL is a data summarization tool that transforms rows into columns, allowing you to reorganize and aggregate data for easier analysis. It helps to summarize and analyze large datasets by grouping and displaying data in a cross-tabular format.</p>



<div style="padding-top: 0.625rem; padding-bottom: 0.3125rem;"><b><i><u>example:</u></i></b></div>



<pre class="pchl"><code><span class="key">SELECT</span> *
<span class="key">FROM</span> (
    <span class="key">SELECT</span> Month, Product, Sales
    <span class="key">FROM</span> SalesData
) <span class="key">AS</span> SourceTable
PIVOT (
    SUM(Sales)
    <span class="key">FOR</span> Month <span class="key">IN</span> ([Jan], [Feb], [Mar], [Apr])
) <span class="key">AS</span> PivotTable; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>What is SQL injection?</strong></h3>



<p class="custp1"><strong>SQL injection</strong> is a type of cyber attack where an attacker inserts malicious SQL code into an input field, potentially allowing them to manipulate the database and access unauthorized data.</p>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>How to Prevent SQL Injection</strong></h3>



<br>



<ol class="ol1 wp-block-list">
<li><strong>Use Prepared Statements</strong>: Parameterize queries to separate SQL code from data.</li>



<li><strong>Use Stored Procedures</strong>: Encapsulate SQL queries within stored procedures.</li>



<li><strong>Validate Input</strong>: Ensure that input data is properly validated and sanitized.</li>



<li><strong>Limit Database Permissions</strong>: Restrict user permissions to only what is necessary.</li>



<li><strong>Use ORM Libraries</strong>: Object-Relational Mapping libraries often handle parameterization automatically.</li>
</ol>



<br><br>



<h3 class="wp-block-heading hLBRed"><strong>Write syntax to create a stored procedure.</strong></h3>



<pre class="pchl"><code><span class="key">CREATE</span> <span class="key">PROCEDURE</span> GetEmployeesByDepartment
    @DeptID INT
<span class="key">AS</span>
<span class="key">BEGIN</span>
    <span class="key">SELECT</span> * 
    <span class="key">FROM</span> Employees 
    <span class="key">WHERE</span> DepartmentID = @DeptID;
<span class="key">END</span></code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>How to prevent duplicate records when making a query?</strong></strong></h3>



<br>



<p class="p-mb-0"><strong>1)</strong> Using the&nbsp;<span class="spanHT">DISTINCT</span>&nbsp;statement with <span class="spanHT">SELECT</span></p>



<pre class="pchl"><code><span class="key">SELECT <b>DISTINCT</b></span> column1, ... <span class="key">FROM</span> table_name </code></pre>



<p class="custp1 p-mb-0"><strong>2)</strong> Using <span class="spanHT">GROUP BY</span></p>



<pre class="pchl"><code><span class="key">SELECT</span> FirstName, LastName
<span class="key">FROM</span> Employees
<span class="key"><b>GROUP BY</b></span> FirstName, LastName; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How to find the last ID (number) in a table? </strong></h3>



<br>



<p class="p-mb-0"><strong>1)</strong> Using the <span class="spanHT">MAX()</span> function.</p>



<pre class="pchl"><code><span class="key">SELECT</span> <span style="color:#FF33CC; background:#f2f19d;"><b>MAX</b>(ID)</span> <span class="key">AS</span> LastID <span class="key">FROM</span> TableName; </code></pre>



<p class="custp1 p-mb-0"><strong>2)</strong> Using <span class="spanHT">TOP</span> and <span class="spanHT">ORDER BY</span></p>



<pre class="pchl"><code><span class="key">SELECT <span style="background:#f2f19d;"><b>TOP</b></span></span> 1 ID <span class="key">FROM</span> TableName <span class="key" style="background:#f2f19d;"><b>ORDER BY</b></span> ID DESC; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How to find 6th highest salary</strong></h3>



<br>



<p class="p-mb-0">You can use the <span class="spanHT">ROW_NUMBER()</span> function</p>



<pre class="pchl"><code><span class="key">SELECT</span> Salary
<span class="key">FROM</span> (
    <span class="key">SELECT</span> Salary, <span style="background:#f2f19d;"><b>ROW_NUMBER()</b></span> <span class="key">OVER</span> (ORDER <span class="key">BY</span> Salary <span class="key">DESC</span>) <span class="key">AS</span> RowNum
    <span class="key">FROM</span> Employees
) <span class="key">AS</span> RankedSalaries
<span class="key">WHERE</span> RowNum = 6; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong><strong>How to find the values in a text column of a table that start with a certain letter?</strong></strong></h3>



<br>



<p class="p-mb-0">Use <span class="spanHT">LIKE</span> operator with <span class="spanHT">%</span></p>



<pre class="pchl"><code><span class="key">SELECT</span> * <span class="key">FROM</span> Employees <span class="key">WHERE</span> Name <span style="background:#f2f19d;"><span class="key">LIKE</span> 'G%'</span> </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How to select random rows from a table?</strong></h3>



<br>



<p class="p-mb-0">Using the <span class="spanHT">NEWID()</span> function</p>



<pre class="pchl"><code><span class="key">SELECT</span> * <span class="key">FROM</span> TableName <span class="key">ORDER BY</span> <span style="background:#f2f19d;"><span style="color:#FF33CC;"><b>NEWID</b><span>()</span>; </code></pre>



<br><br><br>



<h4 class="wp-block-heading hLBRed"><strong>How can you create a new table with the same structure as an existing table?</strong></h4>



<br>



<p class="p-mb-0">Using the <span class="spanHT">INTO</span> operator with a <span class="spanHT">WHERE</span> clause that is always false for all records.</p>



<pre class="pchl"><code><span class="key">SELECT</span> * <span style="background:#f2f19d;"><span class="key">INTO</span> Employee_copy</span>
<span class="key">FROM</span> Employee <span class="key">WHERE</span> 1 = 2; </code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed"><strong>How can database performance be improved?</strong></h3>



<p class="custp1 p-mb-0">Measures to Increase Database Performance:</p>



<ul class="ol1 wp-block-list">
<li><strong>Indexing:</strong> Create indexes on frequently queried columns to speed up searches.</li>



<li><strong>Query Optimization:</strong> Write efficient SQL queries, avoid unnecessary columns in SELECT, and use proper JOINs.</li>



<li><strong>Normalization:</strong> Normalize data to reduce redundancy and improve data integrity.</li>



<li><strong>Denormalization:</strong> Use denormalization where necessary to reduce JOIN operations and improve read performance.</li>



<li><strong>Partitioning:</strong> Split large tables into smaller, manageable pieces (partitions) for faster access.</li>



<li><strong>Caching:</strong> Use caching mechanisms to store frequently accessed data in memory.</li>



<li><strong>Load Balancing:</strong> Distribute database load across multiple servers.</li>



<li><strong>Hardware Upgrades:</strong> Upgrade to faster CPUs, add more RAM, and use SSDs for better performance.</li>



<li><strong>Regular Maintenance:</strong> Perform routine maintenance like updating statistics, rebuilding indexes, and cleaning up logs.</li>



<li><strong>Connection Pooling:</strong> Use connection pooling to reuse database connections efficiently.</li>



<li><strong>Database Configuration:</strong> Optimize database configuration settings for performance.</li>



<li><strong>Monitoring and Profiling:</strong> Monitor database performance and profile queries to identify and address bottlenecks.</li>
</ul>



<br><br>



<style>
.shbtn {
    color: #fff;
    padding: 6px 12px;
    margin-top: 8px;
}
</style>



<br>
<div id="download-questions" style="border: solid 1px lightblue; padding: 10px;">
<button class="shbtn" style="float: right; border-radius: 20px;" onclick="saveQuestionsAsPDF()">Download</button>
<div><span style="font-weight: bold; font-size: 20px; color: #7100e2;">Download all Questions as .PDF</span></div>
<div id="questions"><br><br><center><span style="color:#808080;"><i>loading&#8230;</i></span></center></div>
</div>



<br>
<div id="PageInAd1"></div>
<script>
fetch('/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<br><br>
<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="3,59,71">
<div id="latestPostlist"></div>
<br>



<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>



<script>
window.onload = function (){
	/*Sl.No for H3*/
	var h3arr = document.getElementsByClassName("hLBRed");
	var questions = document.getElementById("questions");
	questions.innerHTML = "<br><br><div><h2><center><b><u>SQL Interview Questions</u></b></center></h2></div><br>";
	var count = 1;
	var searchResult = "";
	for (h3 of h3arr) {
		questions.innerHTML = questions.innerHTML + "<div>" + "<b>" + count + ")</b> " + h3.innerText.replace(/[^\w\s#?.,=<>]/gi, '').replace('<','&lt;').replace('>','&gt;') + "</div>";
		h3.innerHTML = "<b>" + count + ") " + h3.innerHTML + "</b>";
		h3.id = "q" + count;
		searchResult += '<div class="filter-list-item"><a href="#' + h3.id + '">' + h3.innerText + '</a></div>'
		count++;
	}

	document.getElementById('myList').innerHTML = searchResult;
};


/* Print Questions */
function saveQuestionsAsPDF(divId, title) { 
	if (document.getElementById("questions").innerText.trim().length == 0) return;

	var doc = new jsPDF();
	doc.fromHTML('<html><head></head><body><div>https://www.codeindotnet.com/all-interview-questions-and-answers/</div>' + document.getElementById("questions").innerHTML + '<br><br><br><div><b>See Other Questions &amp; Answers:</b> https://www.codeindotnet.com/all-interview-questions-and-answers/</div></body></html>');
	doc.save('sql-interview-questons.pdf');
}

</script>



<script type="text/javascript">
        document.getElementById("myInput").addEventListener("keyup",
    		function searchFilter() {
    			// Declare variables
    			var input, filter, div, divs, a, i;
    			input = document.getElementById('myInput').value.replace(/\s{2,}/g, ' ').trim().toUpperCase();
				arrFilters = input.split(' ');
    			div = document.getElementById('myList');
    			divs = div.getElementsByClassName('filter-list-item');
				
    			if (document.getElementById("myList").style.display == "none"){
    				document.getElementById("myList").style.display = "block";
    			}

				if(input.length == 0){
					for (i = 0; i < divs.length; i++) {
						divs[i].style.display = '';						
					}
				}
				else {
					// Loop through all list items, and hide those who don't match the search query
					for (i = 0; i < divs.length; i++) {
						a = divs[i].getElementsByTagName('a')[0];
						divs[i].style.display = 'none';
						for (j = 0; j < arrFilters.length; j++) {
							if ((arrFilters[j].length > 0) && (a.innerHTML.toUpperCase().indexOf(arrFilters[j]) > -1)) {
								divs[i].style.display = '';
								break;
							} 						
						}
						
					}
				}
    
		});
    </script>



<script>
function displayAllResult(){
	document.getElementById("myInput").value = ''
	div = document.getElementById('myList');
	divs = div.getElementsByClassName('filter-list-item');
	for (i = 0; i < divs.length; i++) {
		divs[i].style.display = '';						
	}
}
</script>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/sql-interview-questions-answers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
