<?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>C# - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Sun, 09 Jun 2024 21:25:22 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>C# - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Check Which Version of C# App is using</title>
		<link>https://thecodebuzz.com/how-to-check-the-version-of-csharp-windows-mac-linux/</link>
					<comments>https://thecodebuzz.com/how-to-check-the-version-of-csharp-windows-mac-linux/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 28 Oct 2023 01:28:14 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=28598</guid>

					<description><![CDATA[<p>How to Check the Version of C# Today in this article, we shall see how to check which version of C# your Application is using. We will see various easy-to-use techniques to verify the version. The below techniques can be used to verify the version on your developer machines or build a machine or cloud [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/how-to-check-the-version-of-csharp-windows-mac-linux/">How to Check Which Version of C# App is using</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading"><strong>How to Check the Version of C# </strong></h1>



<figure class="wp-block-image"><img fetchpriority="high" decoding="async" width="1024" height="397" src="https://www.thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-1024x397.jpg" alt="which-version-of-c-sharp-using" class="wp-image-19445" srcset="https://thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-1024x397.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-300x116.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-768x298.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-1536x596.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-785x304.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application.jpg 1547w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Today in this article, we shall see how to check which version of C# your Application is using.</p>



<p><br>We will see various easy-to-use techniques to verify the version. The below techniques can be used to verify the version on your developer machines or build a machine or cloud server.</p>



<p></p>



<p>You may find the need to check the C# version on the hosted application or server or in a cloud container etc.</p>



<p></p>



<p>We will cover the below aspects in the article,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-get-c-version-using-command-prompt">Get C# Version using Command line (Windows/Linux/MacOS)</a><ul><li><a href="#aioseo-command">Command</a></li></ul></li><li><a href="#aioseo-get-c-version-using-error-directive">Get C# Version using #Error Directive</a><ul><li><a href="#aioseo-command">Command</a></li></ul></li><li><a href="#aioseo-check-net-core-version--sdk-and-runtime-version-programmatically">Check .NET Core version- SDK and Runtime version Programmatically</a><ul><li><a href="#aioseo-command">Command</a></li></ul></li><li><a href="#aioseo-c-version-using-visual-studio---option-is-disabled">C# Version using Visual Studio &#8211; Option is disabled now</a></li><li><a href="#aioseo-check-all-supported-c-version-till-date">Check all supported C# versions to date</a></li><li><a href="#aioseo-how-to-target-specific-version">How to Target specific version</a></li></ul></div>



<p></p>



<p>Please note that as per recent guidelines from Microsoft default version of C#  used by the application will be driven by the underlying .NET framework used (This is true for .NET or .NET Core framework used).</p>



<p></p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-c-version-using-visual-studio---option-is-disabled"></h2>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-get-c-version-using-command-prompt">Get C# Version using Command line (Windows/Linux/MacOS)</h2>



<p></p>



<p>Using any Shell or CLI ex. <strong><em>Visual Studio </em></strong>Command prompt:</p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-command">Command</h3>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size"><strong>csc /langversion:?</strong>
</pre>



<figure class="wp-block-image"><a href="https://www.thecodebuzz.com/how-to-get-a-version-of-c-sharp-language-build-server-cloud" target="_blank" rel="noopener"><img decoding="async" width="784" height="492" src="https://www.thecodebuzz.com/wp-content/uploads/2021/11/check-c-language-used-on-server.jpg" alt="which-c-sharp-version-net-core-uses get a version of the C# language" class="wp-image-19446" srcset="https://thecodebuzz.com/wp-content/uploads/2021/11/check-c-language-used-on-server.jpg 784w, https://thecodebuzz.com/wp-content/uploads/2021/11/check-c-language-used-on-server-300x188.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/11/check-c-language-used-on-server-768x482.jpg 768w" sizes="(max-width: 784px) 100vw, 784px" /></a></figure>



<p></p>



<p>C# compiler determines a default language version based on your project&#8217;s target framework.  The target project when built gets the highest compatible language version by default as per this versioning semantics. </p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-get-c-version-using-error-directive">Get C# Version using #Error Directive</h2>



<p></p>



<p>One can use the below directive to verify the c# language version.<em><strong> </strong></em></p>



<p></p>



<p><em><strong>Just type the below command anywhere in .cs file and mouse hover on it </strong></em></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-command">Command</h3>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size"><strong>#error version</strong><br><br></pre>



<figure class="wp-block-image size-large"><a href="https://www.thecodebuzz.com/how-to-get-a-version-of-c-sharp-language-build-server-cloud" target="_blank" rel="noopener"><img decoding="async" width="1024" height="319" src="https://www.thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-using-cs-file-1024x319.jpg" alt="what-are-the-correct-version-numbers-for-c-sharp" class="wp-image-19447" srcset="https://thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-using-cs-file-1024x319.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-using-cs-file-300x94.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-using-cs-file-768x240.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-using-cs-file-785x245.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2021/11/which-version-of-c-sharp-used-application-using-cs-file.jpg 1375w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-check-net-core-version--sdk-and-runtime-version-programmatically">Check .NET Core version- SDK and Runtime version Programmatically</h2>



<p></p>



<p>Additionally, if you are interested in knowing what version of .NET Core or framework is installed please follow the techniques discussed below,</p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-command">Command</h3>



<p></p>



<pre class="wp-block-preformatted">dotnet --list-sdks</pre>



<p></p>



<p>For more details on the commands, please visit the below article,</p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/get-sdk-and-runtime-version-net-core/" target="_blank" rel="noopener" title="How to Check .NET Core version installed SDK and Runtime"><em><strong>How to Check .NET Core version installed SDK and Runtime</strong></em></a></li>
</ul>



<p></p>



<h2 class="wp-block-heading" id="aioseo-c-version-using-visual-studio---option-is-disabled">C# Version using Visual Studio &#8211; Option is disabled now</h2>



<p></p>



<p>Previously it used to be easy to find C# vesion by navigating the Project- Properties-&gt; Build tab.</p>



<p></p>



<p>However as per new guidelines (explained below).. The visual studio above option is disabled.</p>



<p></p>



<p><strong>As per Microsoft guidelines </strong></p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Moving forward, however, each version of each framework will have a <strong>single supported </strong>and <strong>default</strong> version, and we won’t support arbitrary versions. To reflect this change in support, this commit permanently disables the language version combo box and adds a link to a document explaining the change.</p>
</blockquote>



<p></p>



<p><em>So if using .NET or .NET Core then the framework will always target only a single language version and which will also be a default version. </em></p>



<p></p>



<p>The default version will be a <strong>major </strong>version of C#.</p>



<p></p>



<p>So with the above guidelines Visual Studio option to check or update the C# language version is disabled.</p>



<p></p>



<p><strong><em>Project > Properties > Build > Advanced </em></strong>option is <strong><em>disabled</em></strong>.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-check-all-supported-c-version-till-date">Check all supported C# versions to date </h2>



<p></p>



<p>Please visit the below Microsoft list,</p>



<p></p>



<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version#c-language-version-reference" target="_blank" rel="noopener" title="">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version#c-language-version-reference</a></p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-how-to-target-specific-version">How to Target specific version </h2>



<p></p>



<p>If you need to change or target your application to use a particular C# <a href="https://www.thecodebuzz.com/modifier-not-valid-this-item-c-use-language-version-greater/">language version</a>, then there are various approaches to achieve this. Please refer to the below article, </p>



<p></p>



<ul class="wp-block-list">
<li><strong><em><a href="https://www.thecodebuzz.com/enable-c-sharp-language-version-guidelines/" target="_blank" rel="noreferrer noopener" title="How to Enable C# Language Versioning – Guidelines">How to Enable C# Language Versioning – Guidelines</a></em></strong></li>
</ul>



<p></p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/how-to-check-the-version-of-csharp-windows-mac-linux/">How to Check Which Version of C# App is using</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/how-to-check-the-version-of-csharp-windows-mac-linux/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>C# Read file as Key value Dictionary pair</title>
		<link>https://thecodebuzz.com/c-read-file-as-key-value-dictionary-pair/</link>
					<comments>https://thecodebuzz.com/c-read-file-as-key-value-dictionary-pair/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 22 Oct 2023 18:17:21 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[csharp-file-as-key-value-dictionary]]></category>
		<category><![CDATA[csharp-read-file-as-key-value-dictionary-pair-net]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=28584</guid>

					<description><![CDATA[<p>C# Read file as Key value Dictionary pair Today in this article, we will see how to Read files as Key value Dictionary pairs using a simple and effective approach. Using this approach you can generate a Dictionary list of possible values. To keep it simple we will use the below file where we have [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/c-read-file-as-key-value-dictionary-pair/">C# Read file as Key value Dictionary pair</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">C# Read file as Key value Dictionary pair</h1>



<p>Today in this article, we will see how to Read files as Key value Dictionary pairs using a simple and effective approach.</p>



<p></p>



<p>Using this approach you can generate a Dictionary list of possible values.</p>



<p></p>



<p>To keep it simple we will use the below file where we have content separated by<strong> pipe delimiter</strong>.</p>



<p></p>



<p>However, the below-discussed approach can be used for other separator like comma-separated values(,) or space( ) or any other separator, etc.</p>



<p>  </p>



<p></p>



<p><strong>Sample file </strong></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="368" src="https://www.thecodebuzz.com/wp-content/uploads/2023/10/c-sharp-dictionary-how-to-read-key-value-from-file-1024x368.jpg" alt="" class="wp-image-28585" srcset="https://thecodebuzz.com/wp-content/uploads/2023/10/c-sharp-dictionary-how-to-read-key-value-from-file-1024x368.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/10/c-sharp-dictionary-how-to-read-key-value-from-file-300x108.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/10/c-sharp-dictionary-how-to-read-key-value-from-file-768x276.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/10/c-sharp-dictionary-how-to-read-key-value-from-file-1536x552.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2023/10/c-sharp-dictionary-how-to-read-key-value-from-file-785x282.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/10/c-sharp-dictionary-how-to-read-key-value-from-file.jpg 1802w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p></p>



<p>Below is a sample code of how we can read the content and create a <strong>dictionary </strong>of key values pair using Employee ID as Key and Employee Name as Value.</p>



<p></p>



<p>Below fileLineReader is each line from the target file. It read the content and split the data using the &#8220;I&#8221; pipe delimiter. </p>



<p></p>



<h2 class="wp-block-heading">File with Pipe Delimiter</h2>



<p></p>



<pre class="wp-block-preformatted">                   string[] keyvalue = fileLineReader.Current.Split('|');
                    if (keyvalue.Length == 3)
                    {
                        employeeDict.Add(keyvalue[1], keyvalue[0]);
                    }</pre>



<p></p>



<p>Below sample code using File Emuerator </p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="508" src="https://www.thecodebuzz.com/wp-content/uploads/2023/10/Csharp-Dictionary-how-to-read-keyvalue-from-file-1024x508.jpg" alt="C# Read file as Key value Dictionary " class="wp-image-28586" srcset="https://thecodebuzz.com/wp-content/uploads/2023/10/Csharp-Dictionary-how-to-read-keyvalue-from-file-1024x508.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/10/Csharp-Dictionary-how-to-read-keyvalue-from-file-300x149.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/10/Csharp-Dictionary-how-to-read-keyvalue-from-file-768x381.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/10/Csharp-Dictionary-how-to-read-keyvalue-from-file-1536x761.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2023/10/Csharp-Dictionary-how-to-read-keyvalue-from-file-2048x1015.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2023/10/Csharp-Dictionary-how-to-read-keyvalue-from-file-785x389.jpg 785w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">#image_title #separator_sa #post_seo_title</figcaption></figure>



<p></p>



<h2 class="wp-block-heading">Parse File line with Space</h2>



<p></p>



<pre class="wp-block-preformatted">string[] keyvalue = fileLineReader.Current.Split(' ');
                    if (keyvalue.Length == 3)
                    {
                        employeeDict.Add(keyvalue[1], keyvalue[0]);
                    }</pre>



<p></p>



<h2 class="wp-block-heading">Parse File line with comma-separated values</h2>



<p></p>



<pre class="wp-block-preformatted">string[] keyvalue = fileLineReader.Current.Split(' ');
                    if (keyvalue.Length == 3)
                    {
                        employeeDict.Add(keyvalue[1], keyvalue[0]);
                    }</pre>



<p></p>



<p></p>



<p></p>



<p>Are you dealing with a huge file that needs chunking logic to be used due to its size? </p>



<p></p>



<p>If you have a huge file size to deal with then it&#8217;s important to check the performance of the filter or query.</p>



<p> Kindly check below 2-3 approaches discussed below for effective chunking and converting the file into a dictionary.</p>



<p></p>



<p></p>



<p>Kindly visit below a few useful articles on dealing with file size, </p>



<p></p>



<ul class="wp-block-list">
<li> <a href="https://www.thecodebuzz.com/read-large-file-into-a-byte-array-with-chunks-csharp/" title="Read a Large File in Chunks in C# Guidelines">Read a Large File in Chunks in C# Guidelines</a>?</li>
</ul>



<p></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/c-read-file-as-key-value-dictionary-pair/">C# Read file as Key value Dictionary pair</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/c-read-file-as-key-value-dictionary-pair/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Send Email in ASP.NET Core using MailKit with Attachments</title>
		<link>https://thecodebuzz.com/mailkit-send-email-in-asp-net-core-3-1/</link>
					<comments>https://thecodebuzz.com/mailkit-send-email-in-asp-net-core-3-1/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 17 Oct 2023 02:22:00 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET 7 mailkit]]></category>
		<category><![CDATA[asp.net core .NET 6]]></category>
		<category><![CDATA[asp.net core 3.1 send email]]></category>
		<category><![CDATA[asp.net core mailkit]]></category>
		<category><![CDATA[asp.net core mailkit tutorial]]></category>
		<category><![CDATA[asp.net core send email]]></category>
		<category><![CDATA[c mailkit send attachment]]></category>
		<category><![CDATA[c# mailkit gmail example]]></category>
		<category><![CDATA[c# mailkit smtp example]]></category>
		<category><![CDATA[email .net5]]></category>
		<category><![CDATA[how to use mailkit in c#]]></category>
		<category><![CDATA[mailkit .net core 3.1]]></category>
		<category><![CDATA[mailkit .net core 5]]></category>
		<category><![CDATA[mailkit attach csvf]]></category>
		<category><![CDATA[mailkit attach doc]]></category>
		<category><![CDATA[mailkit attach excel]]></category>
		<category><![CDATA[mailkit attach html]]></category>
		<category><![CDATA[mailkit attach pdf]]></category>
		<category><![CDATA[mailkit dispose]]></category>
		<category><![CDATA[mailkit embed image]]></category>
		<category><![CDATA[mailkit multiple recipients]]></category>
		<category><![CDATA[mailkit net core]]></category>
		<category><![CDATA[mailkit net core 2]]></category>
		<category><![CDATA[mailkit send attachment]]></category>
		<category><![CDATA[mailkit smtpclient attachment]]></category>
		<category><![CDATA[mailkit vb.net example]]></category>
		<category><![CDATA[mailkit vs smtpclient]]></category>
		<category><![CDATA[mimekit mailmessage]]></category>
		<category><![CDATA[Send Email in ASP.NET Core using MailKit]]></category>
		<category><![CDATA[Send email mailkit attach csvf]]></category>
		<category><![CDATA[Send email mailkit attach doc]]></category>
		<category><![CDATA[Send email mailkit attach excel]]></category>
		<category><![CDATA[Send email mailkit attach html]]></category>
		<category><![CDATA[Send email mailkit attach pdf]]></category>
		<category><![CDATA[Send email mailkit embed image]]></category>
		<category><![CDATA[Send email mailkit smtpclient attachment]]></category>
		<category><![CDATA[smtp .net5 smtp .net 6]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=7600</guid>

					<description><![CDATA[<p>Send Email in ASP.NET Core using MailKit with Attachments Today in this article, we will see how to use MailKit a C# .NET library. We will send emails in ASP.NET Core using MailKit. We will use ASP.NET .NET 6 application examples. We shall also see how to send an email using attachments i.e. we will [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/mailkit-send-email-in-asp-net-core-3-1/">Send Email in ASP.NET Core using MailKit with Attachments</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Send Email in ASP.NET Core using MailKit with Attachments</h1>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" width="1024" height="404" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-1024x404.jpg" alt="Send Email c# mailkit, MailKit " class="wp-image-7620" style="width:964px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-1024x404.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-300x118.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-768x303.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-1536x606.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap-785x310.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-server-pop-imap.jpg 1903w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Today in this article, we will see how to use <strong>MailKit </strong>a C# .NET library. </p>



<p></p>



<p>We will send emails in ASP.NET Core using MailKit. We will use ASP.NET .NET 6 application examples. </p>



<p></p>



<p>We shall also see how to send an email using attachments i.e. we will attach files like PDF or HTML or Images or Word doc files etc as attachments to emails we are sending to our users.</p>



<p><br>We will cover the below aspects in today&#8217;s article,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-what-is-mailkit">What is MailKit</a></li><li><a href="#aioseo-getting-started">Getting Started</a><ul><li><a href="#aioseo-create-asp-net-core-3-1-or-net-5-0-api">Create ASP.NET Core 3.1 or .NET 6.0 API</a></li></ul></li><li><a href="#aioseo-send-email-in-asp-net-core-using-mailkit---define-mimemessage-structure">Send Email in ASP.NET Core using MailKit &#8211; Define MimeMessage structure</a></li><li><a href="#aioseo-define-smtp-c-mailkit-client">Define SMTP C# MailKit Client</a></li><li><a href="#aioseo-send-email-with-attachment-html-or-jpeg-or-pdf-files">Send Email with Attachment (HTML or . JPEG or . PDF files)</a></li><li><a href="#aioseo-using-mimekit-bodybuilder">Using MimeKit.BodyBuilder</a></li><li><a href="#aioseo-sending-multiple-attachments">Sending multiple Attachments using MailKit</a></li><li><a href="#aioseo-using-gmail-smtp-server">Using Gmail SMTP server with MailKit</a></li><li><a href="#aioseo-retrieving-messages-via-pop3">Retrieving Messages (via Pop3)</a></li><li><a href="#aioseo-retrieving-messages-via-imap">Retrieving Messages (via IMAP )</a></li><li><a href="#aioseo-other-advantages-of-mailkit">Other Advantages of MailKit</a></li><li><a href="#aioseo-differences-between-smtp-vs-mailkit">Differences between SMTP Vs MailKit</a></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p></p>



<p></p>



<div data-schema-only="false" class="wp-block-aioseo-faq" id="aioseo-what-is-mailkit"><h3 class="aioseo-faq-block-question">What is MailKit</h3><div class="aioseo-faq-block-answer">
<p>MailKit is a powerful open-source library for .NET that allows developers to easily send, receive, and manipulate email messages. </p>



<p></p>



<p>MailKit provides extensive support for email protocols like <strong>SMTP</strong>, <strong>POP3</strong>, and <strong>IMAP</strong>, making it a comprehensive solution for email communication. </p>



<p></p>



<p>It is commonly used in .NET Core applications for email-related functionalities.</p>



<p></p>



<p> <em>It supports most of the modern protocols</em> and <em>is also optimized for mobile devices</em></p>
</div></div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p></p>



<p></p>
</blockquote>



<p> I was looking to build send email functionality as a Service using C# .NET Core 3.1 recently using <strong>MailKit</strong>. </p>



<p></p>



<p>The service’s core functionality was to send emails using the registered <strong>SMTP </strong>server.  </p>



<p></p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>As per Microsoft&nbsp;<strong><a href="https://www.thecodebuzz.com/send-email-in-net-core/" target="_blank" rel="noreferrer noopener" title="Send Email in .NET Core">Send emails using SmtpClient</a>&nbsp;</strong>is good for one-off emails from tools but doesn’t scale to modern requirements of the protocol.  </p>



<p></p>



<p>It’s recommended to use <strong>MailKit&nbsp;</strong>or <strong>MimeKit or </strong>other libraries for any scaled and additional protocol requirements. </p>



<p></p>



<p>So if the requirement is simple enough to send an email <em><strong>SmtpClient</strong>&nbsp;</em>approach will still work for you.  </p>
</blockquote>



<p></p>



<p>I found that .NET Core has full support for email functionality using <strong>MailKit</strong>. </p>



<p></p>



<p>Let&#8217;s send an email from the Gmail mail server (<strong>smtp.gmail.com</strong>) to another domain (<em><a href="mailto:info@thecodebuzz.com" target="_blank" rel="noreferrer noopener"><span class="has-inline-color has-vivid-cyan-blue-color">infoATthecodebuzz.com</span></a></em>) for this article.</p>



<p></p>



<p>I have used my own <strong>Gmail </strong>for sending an email and testing purposes which worked very well after some initial travail.</p>



<p></p>



<p>MailkIt gives <strong>RFC</strong>-compliant <strong>SMTP</strong>, <strong>POP3</strong>, and <strong>IMAP </strong>client implementations.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-getting-started">Getting Started</h2>



<p></p>



<h4 class="wp-block-heading" id="aioseo-create-asp-net-core-3-1-or-net-5-0-api">Create ASP.NET Core 3.1 or .NET 6.0 API</h4>



<p></p>



<figure class="wp-block-image is-resized"><img decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/mailkit-send-email-asp-net-core-3-1024x575.jpg" alt="embed image in email,MailKit with Attachments" class="wp-image-7602" style="width:738px;height:auto"/></figure>



<p></p>



<p>Please add below <strong><a href="https://www.nuget.org/packages/MailKit/" target="_blank" rel="noreferrer noopener">Nuget </a></strong>packages to the project,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">PM&gt; Install-Package MailKit -Version &lt;version&gt;</pre>



<p></p>



<p><strong>Note</strong>&#8211; Please u<em>se the <strong>latest available </strong>version.</em></p>



<p></p>



<p>We shall be using the POST method for sending out an email. </p>



<p></p>



<p>Please add the below namespace to your file,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">using MailKit.Net.Smtp;


using MimeKit;</pre>



<p></p>



<p>Let’s write the below code for the POST method.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-send-email-in-asp-net-core-using-mailkit---define-mimemessage-structure">Send Email in ASP.NET Core using MailKit &#8211; Define MimeMessage structure</h2>



<p></p>



<p>As a first step please define the <strong>MimeMessage</strong> structure.</p>



<p></p>



<p>A message structure consists of header fields and a body. The body of the message can be plain text or a tree of <strong><em>MIME </em></strong>entities.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
var message = new MimeMessage();
                message.From.Add(new MailboxAddress(&quot;TheCodeBuzz&quot;, &quot;xxxx@gmail.com&quot;));
                message.To.Add(new MailboxAddress(&quot;TheCodeBuzz&quot;, &quot;infoATthecodebuzz.com&quot;));
                message.Subject = &quot;My First Email&quot;;
                message.Body = new TextPart(&quot;plain&quot;)
                {
                    Text = emailData
                };
</pre></div>


<p></p>



<h2 class="wp-block-heading" id="aioseo-define-smtp-c-mailkit-client">Define SMTP C# MailKit Client</h2>



<p></p>



<p>Let&#8217;s now define the <strong>SMTP MailKit </strong>client. </p>



<p></p>



<p>We shall pass the <strong><em>MimeMessage </em></strong>object to the Send() API as below,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
using (var client = new MailKit.Net.Smtp.SmtpClient())
          {
                       client.Connect(&quot;smtp.gmail.com&quot;, 587, false);
                        //SMTP server authentication if needed
                        client.Authenticate(&quot;xxxx@gmail.com&quot;, &quot;xxxxx&quot;);
                        client.Send(message);
                        client.Disconnect(true);
                       
          }
</pre></div>


<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong><em>Above </em></strong>GMAIL <strong><em>SMTP </em></strong>using <em><strong>587 </strong></em>as a standards port for the communication.</p>
</blockquote>



<p></p>



<p>Complete the POC example demonstrating the usage as below. </p>



<p></p>



<p>You can very much use the below code in any module as suitable to your <strong><em>layered code structure</em></strong>.</p>



<p></p>



<p><strong><em>Example</em></strong></p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
        &#x5B;HttpPost]
        public ActionResult&lt;IEnumerable&lt;bool&gt;&gt; 
        SendEmail(&#x5B;FromBody] string emailData)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(&quot;TheCodeBuzz&quot;, &quot;xxxx@gmail.com&quot;));
                message.To.Add(new MailboxAddress(&quot;TheCodeBuzz&quot;, &quot;infoATthecodebuzz.com&quot;));
                message.Subject = &quot;My First Email&quot;;
                message.Body = new TextPart(&quot;plain&quot;)
                {
                    Text = emailData
                };
                
                    using (var client = new MailKit.Net.Smtp.SmtpClient())
                    {
                        client.Connect(&quot;smtp.gmail.com&quot;, 587, false);
                        //SMTP server authentication if needed
                        client.Authenticate(&quot;xxxx@gmail.com&quot;, &quot;xxxxx&quot;);
                        client.Send(message);
                        client.Disconnect(true);
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return StatusCode(500, &quot;Error occured&quot;);
            }
            return Ok(true);
        }
</pre></div>


<p></p>



<h2 class="wp-block-heading" id="aioseo-send-email-with-attachment-html-or-jpeg-or-pdf-files">Send Email with Attachment (HTML or . JPEG or . PDF files)</h2>



<p></p>



<p>We often need to send an email with custom attachments like PDF, HTML, Images, or Excel files along with custom text bodies.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-mimekit-bodybuilder">Using MimeKit.BodyBuilder</h2>



<p></p>



<p><strong>BodyBuilder</strong> from <strong>MimeKit</strong> is a helper class for building common MIME body structures and provides you the flexibility to build message structures&#8230;</p>



<p></p>



<p>Please see below how to use the <strong>BodyBuilder</strong> class.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-sending-multiple-attachments">Sending multiple Attachments using MailKit</h2>



<p></p>



<p><strong>MimeKit.BodyBuilder</strong> lets you send multiple attachments in email. Please update the above message. </p>



<p></p>



<p>The body which is defined for text only as below for both text and attachments like pdf and jpeg as shown below,</p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="870" height="318" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/send-email-with-attachment-pdf-html-jpeg.jpg" alt="send email .NET c# with attachment " class="wp-image-9570" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/send-email-with-attachment-pdf-html-jpeg.jpg 870w, https://thecodebuzz.com/wp-content/uploads/2020/04/send-email-with-attachment-pdf-html-jpeg-300x110.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/04/send-email-with-attachment-pdf-html-jpeg-768x281.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/04/send-email-with-attachment-pdf-html-jpeg-785x287.jpg 785w" sizes="auto, (max-width: 870px) 100vw, 870px" /></figure>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-gmail-smtp-server">Using Gmail SMTP server with MailKit</h2>



<p></p>



<p>For the Gmail SMTP server, the above code worked perfectly for me except I had to update a few security settings as mentioned below. </p>



<p></p>



<p>Initially, you might get the below error,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">”<span class="has-inline-color has-vivid-red-color"> The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. “</span></pre>



<p></p>



<p>Gmail by default prevents you from accessing your e-mail account from external applications. </p>



<p></p>



<p>But you can update your security settings to accept the login from the application. </p>



<p></p>



<p>I got an email from Gmail saying “Critical security alert for your linked Google Account”.</p>



<p></p>



<ul class="wp-block-list">
<li>I had to enable “<strong><em>Allow less secure apps: ON”</em></strong> to make the send email API work properly.</li>
</ul>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="2560" height="862" src="https://i0.wp.com/thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2.jpg?fit=785%2C264&amp;ssl=1" alt="send email net core" class="wp-image-2986" srcset="https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2.jpg 2560w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-300x101.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-1024x345.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-768x259.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-1536x517.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-2048x690.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2019/05/send-email-dotnet-core-smtp-gmail-test-2-785x264.jpg 785w" sizes="auto, (max-width: 2560px) 100vw, 2560px" /></figure>



<p></p>



<p>Such errors are more due to the policy configured on the SMTP email server. </p>



<p></p>



<p>Make sure you are following the proper settings and policies required for a secure connection to connect to the SMTP server.</p>



<p></p>



<p>Finally, an email popped up successfully in my other domain mail Inbox from my Gmail ID.</p>



<p></p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="490" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-1024x490.jpg" alt="Send Email in ASP.NET Core using MailKit ,email net core 5 MailKit " class="wp-image-7603" srcset="https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-1024x490.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-300x143.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-768x367.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-1536x734.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server-785x375.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/01/send-email-net-core-3-1-mailkit-gmail-server.jpg 1646w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p></p>



<h2 class="wp-block-heading" id="aioseo-retrieving-messages-via-pop3">Retrieving Messages (via Pop3)</h2>



<p></p>



<p>Apart from sending emails MaiKit library also provides support for retrieving messages from <strong>pop3 </strong>servers.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-retrieving-messages-via-imap">Retrieving Messages (via IMAP )</h2>



<p></p>



<p><strong><em>MailKit </em></strong>library also provides full support for retrieving messages from <strong>IMAP</strong> servers.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-other-advantages-of-mailkit">Other Advantages of MailKit</h2>



<p></p>



<p><strong>Wide Email Protocol Support:</strong></p>



<p></p>



<p>MailKit provides support for multiple email protocols, including SMTP (for sending emails), POP3 (for receiving emails), and IMAP (for more advanced email operations like folder management and searching).</p>



<p></p>



<p><strong>Open-Source and Cross-Platform:</strong> </p>



<p>MailKit is an open-source library, available under the MIT License, making it freely accessible to developers.</p>



<p></p>



<p><strong>High Performance and Efficient:</strong> </p>



<p></p>



<p>MailKit is designed to be high-performance and efficient, optimized for handling large volumes of email messages. It utilizes asynchronous programming patterns (async/await) to avoid blocking threads and ensure responsiveness in applications.</p>



<p></p>



<p><strong>Extensive MIME Support: </strong></p>



<p></p>



<p>MailKit provides extensive support for MIME (Multipurpose Internet Mail Extensions) and allows developers to work with multipart emails, attachments, inline images, and other MIME-related functionalities.</p>



<p></p>



<p><strong>Secured Email Communication:</strong> </p>



<p></p>



<p>MailKit supports secure communication using SSL/TLS protocols, enabling secure connections to email servers and protecting email communication from eavesdropping or interception.</p>



<p></p>



<p>MailKit is designed to be high-performance and efficient, optimized for handling large volumes of email messages. </p>



<p></p>



<p>It utilizes asynchronous programming patterns (async/await) to avoid blocking threads and ensure responsiveness in applications.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-differences-between-smtp-vs-mailkit">Differences between SMTP Vs MailKit</h2>



<p></p>



<p>Please here to understand the high-level differences between <a href="https://www.thecodebuzz.com/send-email-in-net-core/" target="_blank" rel="noopener" title="How to Send Email in .NET Core – SMTP vs MailKit">SMTP Vs MailKit</a></p>



<p></p>



<p><strong><em>Other references </em></strong>: </p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/send-email-in-net-core/" target="_blank" rel="noreferrer noopener"><strong><em>Send Email using SMTP .NET client</em></strong></a></li>
</ul>



<p></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-summary">Summary </h2>



<p></p>



<p>Today in this article we learned how to send an email message using <strong><em>MailKit </em></strong>a .NET open-source library. We understand traditional <strong>SMTPClient</strong> is now obsolete and it&#8217;s recommended to use MailKit or MimeKit for scaled and additional protocol requirements.</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/mailkit-send-email-in-asp-net-core-3-1/">Send Email in ASP.NET Core using MailKit with Attachments</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/mailkit-send-email-in-asp-net-core-3-1/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Differences IndexOutOfRangeException and ArgumentOutOfRangeException</title>
		<link>https://thecodebuzz.com/differences-indexoutofrangeexception-argumentoutofrangeexception/</link>
					<comments>https://thecodebuzz.com/differences-indexoutofrangeexception-argumentoutofrangeexception/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 24 Sep 2023 22:10:40 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[ArgumentOutOfRangeException]]></category>
		<category><![CDATA[IndexOutOfRangeException]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=24712</guid>

					<description><![CDATA[<p>IndexOutOfRangeException and ArgumentOutOfRangeException are exceptions in C# with distinct purposes and use cases. IndexOutOfRangeException is specific to arrays and collections, indicating attempts to access elements using invalid indices. ArgumentOutOfRangeException is a more general-purpose exception used for parameter validation in method calls, signifying that provided arguments do not meet expected criteria. Understanding when and how to [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/differences-indexoutofrangeexception-argumentoutofrangeexception/">Differences IndexOutOfRangeException and ArgumentOutOfRangeException</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<p><code>IndexOutOfRangeException</code> and <code>ArgumentOutOfRangeException</code> are exceptions in C# with distinct purposes and use cases. </p>



<p></p>



<p><strong><code>IndexOutOfRangeException</code> </strong>is specific to arrays and collections, indicating attempts to access elements using invalid indices. </p>



<p></p>



<p><strong><code>ArgumentOutOfRangeException</code> </strong>is a more general-purpose exception used for parameter validation in method calls, signifying that provided arguments do not meet expected criteria. </p>



<p></p>



<p>Understanding when and how to use these exceptions is essential for writing robust and error-tolerant C# code, whether you&#8217;re working with collections or method parameters.</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-indexoutofrangeexception">IndexOutOfRangeException</a><ul><li><a href="#aioseo-key-characteristics-of-indexoutofrangeexception">Key Characteristics of IndexOutOfRangeException</a><ul><li><a href="#aioseo-array-or-collection-indexing">Array or Collection Indexing</a></li><li><a href="#aioseo-zero-based-indexing">Zero-Based Indexing</a></li><li><a href="#aioseo-common-causes-of-exception">Common Causes of Exception</a></li><li><a href="#aioseo-example-of-indexoutofrangeexception">Example of IndexOutOfRangeException</a></li></ul></li></ul></li><li><a href="#aioseo-argumentoutofrangeexception">ArgumentOutOfRangeException</a><ul><li><a href="#aioseo-key-characteristics-of-argumentoutofrangeexception">Key Characteristics of ArgumentOutOfRangeException :</a><ul><li><a href="#aioseo-method-parameters">Method Parameters</a></li><li><a href="#aioseo-custom-validation">Custom Validation</a></li><li><a href="#aioseo-common-causes">Common Causes</a></li><li><a href="#aioseo-example-of-argumentoutofrangeexception">Example of ArgumentOutOfRangeException:</a></li></ul></li></ul></li><li><a href="#aioseo-context-and-use-cases">Characteristic &#8211; Context and Use Cases</a><ul><li><a href="#aioseo-context-and-use-cases">Context and Use Cases</a></li><li><a href="#aioseo-source-of-exception">Source of Exception</a></li><li><a href="#aioseo-typical-causes">Typical Causes of Exception</a></li><li><a href="#aioseo-use-in-parameter-validation">Use in Parameter Validation</a></li><li><a href="#aioseo-custom-error-messages">Custom Error Messages</a></li><li><a href="#aioseo-handling-and-prevention">Handling and Prevention</a></li><li><a href="#aioseo-conclusion">Conclusion</a></li></ul></li></ul></div>



<p>In this comprehensive comparison, we&#8217;ll explore their differences in depth.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-indexoutofrangeexception"><strong>IndexOutOfRangeException</strong></h2>



<p></p>



<p><code>IndexOutOfRangeException</code> is an exception that is specifically associated with operations involving arrays or collections. </p>



<p></p>



<p>This exception is thrown when you attempt to access an element in an array or collection using an index that is outside the valid range of indices for that particular array or collection.</p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-key-characteristics-of-indexoutofrangeexception">Key Characteristics of IndexOutOfRangeException </h3>



<p></p>



<h4 class="wp-block-heading" id="aioseo-array-or-collection-indexing">Array or Collection Indexing</h4>



<p></p>



<p>This exception is primarily related to the indexing of arrays, lists, and other <a href="https://www.thecodebuzz.com/system-text-json-collection-type-dictionary-with-int32-key-not-supported/">collection types</a> in C#. It deals with scenarios where you&#8217;re trying to access elements using an index.</p>



<p></p>



<h4 class="wp-block-heading" id="aioseo-zero-based-indexing">Zero-Based Indexing</h4>



<p></p>



<p>Most arrays and collections in C# use zero-based indexing. In zero-based indexing, the first element has an index of 0, the second element has an index of 1, and so on. The last element&#8217;s index is equal to the length of the array minus one (<code>Length - 1</code>).</p>



<p></p>



<p></p>



<h4 class="wp-block-heading" id="aioseo-common-causes-of-exception">Common Causes of Exception</h4>



<p></p>



<p>The most common cause of <code>IndexOutOfRangeException</code> is attempting to access an element using an index that is either less than 0 or greater than or equal to the length of the array or collection. This means you&#8217;re trying to access an element that doesn&#8217;t exist within the valid range of indices.</p>



<p></p>



<p></p>



<h4 class="wp-block-heading" id="aioseo-example-of-indexoutofrangeexception">Example of <code>IndexOutOfRangeException</code></h4>



<p></p>



<pre class="wp-block-preformatted"><code>int[] numberList= { 1, 2, 3 };</code>

<code>
int value = <code>numberList</code>[4]; // Throws IndexOutOfRangeException
</code></pre>



<p>In this example, we have an array <code>numbers</code> with three elements. </p>



<p></p>



<p>However, when we try to access <code>numbers[4]</code>, we&#8217;re <a href="https://www.thecodebuzz.com/attempted-to-access-an-element-as-a-type-incompatible-with-the-array/">attempting to access an element</a> at index 3, which is outside the valid range of indices (valid indices for this array are 0, 1, and 2). </p>



<p></p>



<p>This results in an <code>IndexOutOfRangeException</code>.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-argumentoutofrangeexception"><strong>ArgumentOutOfRangeException</strong></h2>



<p></p>



<p><code><strong>ArgumentOutOfRangeException</strong></code>, on the other hand, is a more general-purpose exception that can be used in various contexts beyond just arrays and collections. </p>



<p></p>



<p>It is thrown when a method or constructor is invoked with an argument (parameter) that falls outside the valid range of acceptable values as defined by the method&#8217;s documentation or expectations.</p>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-key-characteristics-of-argumentoutofrangeexception">Key Characteristics of ArgumentOutOfRangeException :</h3>



<p></p>



<h4 class="wp-block-heading" id="aioseo-method-parameters">Method Parameters</h4>



<p></p>



<p>This exception typically arises when validating method parameters. It is thrown to indicate that an argument passed to a method is not within the expected range of valid values.</p>



<p></p>



<p></p>



<h4 class="wp-block-heading" id="aioseo-custom-validation">Custom Validation</h4>



<p></p>



<p>Developers often use <code>ArgumentOutOfRangeException</code> to perform custom parameter validation, ensuring that inputs meet certain criteria or constraints defined by the method or constructor.</p>



<p></p>



<p></p>



<h4 class="wp-block-heading" id="aioseo-common-causes">Common Causes</h4>



<p></p>



<p>The most common causes of <code>ArgumentOutOfRangeException</code> include passing an out-of-range value to a method parameter that expects a specific range of values or violating any other parameter-related validation rules defined by the method.</p>



<p></p>



<p></p>



<h4 class="wp-block-heading" id="aioseo-example-of-argumentoutofrangeexception">Example of <code>ArgumentOutOfRangeException</code>:</h4>



<p></p>



<pre class="wp-block-preformatted"><code>void SetAngle(int angle )
{
    if (<code>angle </code> &lt; 0 || <code>angle </code>&gt; 360)
    {
        throw new ArgumentOutOfRangeException(nameof(<code>angle </code>), "Angle is out of range.");
    }
    // other logic
}
</code></pre>



<p>In this example, we have a method <strong><code><code>SetAngle</code></code> </strong>that expects an integer parameter <code><code>angle</code></code>.</p>



<p></p>



<p>The method intends to set the <code>angle</code>, but it has a validation check that ensures the <code>angle</code> is within a valid range (0 to 360 degrees). </p>



<p></p>



<p>If the provided <code><code>angle</code></code>value falls outside this range, an <code>ArgumentOutOfRangeException</code> is thrown with a custom error message.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-context-and-use-cases"><strong>Characteristic &#8211; Context and Use Cases</strong></h2>



<p></p>



<p>Now that we&#8217;ve looked at the individual characteristics of <code>IndexOutOfRangeException</code> and <code>ArgumentOutOfRangeException</code>, let&#8217;s compare them more comprehensively:</p>



<p></p>



<h4 class="wp-block-heading" id="aioseo-context-and-use-cases">Context and Use Cases</h4>



<p></p>



<ul class="wp-block-list">
<li><strong><code>IndexOutOfRangeException</code></strong>: It is specific to array and collection indexing operations. It is used when you attempt to access elements in an array or collection using indices.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><strong><code>ArgumentOutOfRangeException</code></strong>: It is a more general-purpose exception used for parameter validation in method calls. It is thrown when method parameters fall outside the expected range of valid values.</li>
</ul>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-source-of-exception">Source of Exception</h3>



<p></p>



<ul class="wp-block-list">
<li><strong><code>IndexOutOfRangeException</code></strong>: Typically originates from indexing operations (e.g., <code>array[index]</code>, <code>list[index]</code>) where the index provided is invalid.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><strong><code>ArgumentOutOfRangeException</code></strong>: Originates from the method or constructor invocations when an argument provided as a parameter does not meet the expected criteria.</li>
</ul>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-typical-causes">Typical Causes of Exception</h3>



<p></p>



<ul class="wp-block-list">
<li><strong><code>IndexOutOfRangeException</code></strong>:
<ul class="wp-block-list">
<li>Accessing an array or collection with an index less than 0.</li>



<li>Accessing an array or collection with an index greater than or equal to its length or count.</li>



<li>Attempting to access an element in an empty collection.</li>
</ul>
</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><strong><code>ArgumentOutOfRangeException</code></strong>:
<ul class="wp-block-list">
<li>Passing arguments to a method or constructor that fall outside the acceptable range of values defined by the method&#8217;s contract.</li>



<li>Violating parameter-related validation rules defined by the method or constructor.</li>
</ul>
</li>
</ul>



<p></p>



<h3 class="wp-block-heading" id="aioseo-use-in-parameter-validation">Use in Parameter Validation</h3>



<p></p>



<ul class="wp-block-list">
<li><strong><code>IndexOutOfRangeException</code></strong>: Not typically used for parameter validation. It&#8217;s more focused on array and collection indexing scenarios.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><strong><code>ArgumentOutOfRangeException</code></strong>: Commonly used for parameter validation to ensure that arguments provided to methods or constructors adhere to predefined constraints.</li>
</ul>



<p></p>



<h3 class="wp-block-heading" id="aioseo-custom-error-messages">Custom Error Messages</h3>



<p></p>



<p></p>



<ul class="wp-block-list">
<li><strong><code>IndexOutOfRangeException</code></strong>: While you can catch and handle this exception, it is not typically used to provide custom error messages, as it is more concerned with the invalid index itself.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><strong><code>ArgumentOutOfRangeException</code></strong>: It is often used to provide detailed custom error messages that explain why the provided argument is out of range or violates other validation rules.</li>
</ul>



<p></p>



<h3 class="wp-block-heading" id="aioseo-handling-and-prevention">Handling and Prevention</h3>



<p></p>



<p></p>



<ul class="wp-block-list">
<li><strong><code>IndexOutOfRangeException</code></strong>: To prevent this exception, ensure that you use valid indices when accessing array or collection elements. You can handle it by checking array or collection lengths before indexing or using methods like <code>Enumerable.ElementAtOrDefault()</code>.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><strong><code>ArgumentOutOfRangeException</code></strong>: To prevent this exception, perform thorough parameter validation and document the expected valid ranges for method parameters. Handle it by including validation checks within the method or constructor.</li>
</ul>



<p></p>



<h3 class="wp-block-heading" id="aioseo-conclusion">Conclusion</h3>



<p></p>



<p><code>IndexOutOfRangeException</code> and <strong><code>ArgumentOutOfRangeException</code> </strong>are exceptions in C# with distinct purposes and use cases. <strong><code>IndexOutOfRangeException</code> </strong>is specific to arrays and collections, indicating attempts to access elements using invalid indices. <strong><code>ArgumentOutOfRangeException</code> </strong>is a more general-purpose exception used for parameter validation in method calls, signifying that provided arguments do not meet expected criteria. </p>



<p></p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/differences-indexoutofrangeexception-argumentoutofrangeexception/">Differences IndexOutOfRangeException and ArgumentOutOfRangeException</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/differences-indexoutofrangeexception-argumentoutofrangeexception/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>ServiceFilter and TypeFilter differences in .NET</title>
		<link>https://thecodebuzz.com/servicefilter-and-typefilter-differences-in-dot-net-csharp/</link>
					<comments>https://thecodebuzz.com/servicefilter-and-typefilter-differences-in-dot-net-csharp/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Fri, 09 Jun 2023 00:44:39 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ServiceFilter and TypeFilter]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=27527</guid>

					<description><![CDATA[<p>ServiceFilter and TypeFilter differences in .NET Today in this article, we will understand ServiceFilter and TypeFilter differences in .NET. In .NET Core, both ServiceFilter and TypeFilter are used for implementing filters, which are an easy way to address any cross-cutting concerns to the execution pipeline of an application. There are many benefits of Filters as [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/servicefilter-and-typefilter-differences-in-dot-net-csharp/">ServiceFilter and TypeFilter differences in .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">ServiceFilter and TypeFilter differences in .NET</h1>



<p>Today in this article, we will understand ServiceFilter and TypeFilter differences in .NET.</p>



<p></p>



<p>In .NET Core, both ServiceFilter and TypeFilter are used for implementing filters, which are an easy way to address any cross-cutting concerns to the execution pipeline of an application. </p>



<p></p>



<p>There are many benefits of Filters as explained below,</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-benefits-of-filters">Benefits of Filters</h2>



<p></p>



<ul class="wp-block-list">
<li><em>Abstract your repetitive and important cross-cutting concern to commonplace.</em></li>



<li><em>Make your business logic free of addressing those concerns implicitly</em></li>



<li><em>As we know “Code is more often read than write”. The code becomes easy to read and understand.</em></li>



<li><em>Developers can better focus on implementing business functionality.</em></li>
</ul>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-when-to-use-scenarios">When to Use Scenarios</a></li><li><a href="#aioseo-filter-reusability">Reusability of Filter</a><ul><li><a href="#aioseo-servicefilter-better-reusability">ServiceFilter &#8211; Better Reusability</a></li><li><a href="#aioseo-typefilter">TypeFilter &#8211; Normal Reusability</a></li></ul></li><li><a href="#aioseo-filter-configuration">Filter Configuration</a><ul><li><a href="#aioseo-servicefilter">ServiceFilter</a></li></ul></li><li><a href="#aioseo-depdendency-injection-of-additional-parameters">Dependency Injection of additional parameters</a></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p></p>



<p>While they serve a similar purpose, there are some differences between ServiceFilter and TypeFilter</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-when-to-use-scenarios">When to Use Scenarios </h2>



<p></p>



<ul class="wp-block-list">
<li><code>ServiceFilter</code>: This Filter can be applied to a service or middleware during dependency injection. It allows applying the same filter to <em>multiple services or middleware components</em>.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><code>TypeFilter</code>: This Filter directly to a controller or action method i.r classes and methods, providing more fine-grained control over which specific components the filter is applied to.</li>
</ul>



<p></p>



<h2 class="wp-block-heading" id="aioseo-filter-reusability">Reusability of Filter</h2>



<p></p>



<h3 class="wp-block-heading" id="aioseo-servicefilter-better-reusability">ServiceFilter &#8211; Better Reusability </h3>



<p></p>



<p>ServiceFilter provides flexibility and reusability because it can be applied to <em><strong>multiple services or interfaces</strong></em>. </p>



<p>You can register <strong>a filter as a service </strong>and then apply it to multiple services during dependency injection configuration. </p>



<p></p>



<p>This allows you to define a filter once and reuse it in multiple places.</p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-typefilter">TypeFilter &#8211; Normal Reusability </h3>



<p></p>



<p>TypeFilter is more specific to individual <strong>classes or methods</strong>. </p>



<p></p>



<p>It is typically used when you need to apply a filter to a specific class or method and do not require its reuse in other parts of the application.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-filter-configuration">Filter Configuration</h2>



<p></p>



<h3 class="wp-block-heading" id="aioseo-servicefilter">ServiceFilter</h3>



<p></p>



<p>Since the <code>ServiceFilter</code> uses the <strong><em><code>ServiceProvider</code> </em></strong>to <a href="https://www.thecodebuzz.com/resolve-instances-within-configservices-method-asp-net-core/">resolve the instance</a> of the filter. Instance lifetime can be controlled by registering the filter in the startup class.</p>



<p></p>



<p>ServiceFilter can be registered as a service in the <a href="https://www.thecodebuzz.com/dependency-injection-wpf-generic-hostbuilder-net-core/">dependency injection</a> container using the <code><strong>AddScoped</strong></code>, <code><strong>AddTransient</strong></code>, or <strong><code>AddSingleton</code> </strong>methods. </p>



<p></p>



<pre class="wp-block-preformatted"> public void ConfigureServices(IServiceCollection services)
        {
            // Add service filters.
            services.AddScoped&lt;AddHeaderResultServiceFilter&gt;();
            services.AddScoped&lt;SampleActionFilterAttribute&gt;();
         .
         .
         }</pre>



<p></p>



<p>The registered <a href="https://www.thecodebuzz.com/inject-di-service-into-action-filter/">filter can then be applied to services</a> or middleware components by specifying the filter using the <code>[ServiceFilter]</code> attribute or the <code>.AddServiceFilter()</code> method.</p>



<p></p>



<p>Example :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [1]; title: ; notranslate">
        &#x5B;ServiceFilter(typeof(SampleActionFilterAttribute))]
        public IActionResult ServiceFilterTest()
        {
            return Content($&quot;From ServiceFilterTest&quot;);
        }
</pre></div>


<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-depdendency-injection-of-additional-parameters">Dependency Injection of additional parameters</h2>



<p></p>



<p><strong>ServiceFilter </strong>allows you to inject additional parameters into the filter constructor when applying it at the service registration level. </p>



<p></p>



<p>These additional parameters can be resolved from the dependency injection container and provided to the filter constructor.</p>



<p></p>



<p><strong>TypeFilter </strong>supports the constructor injection of additional parameters through attributes. </p>



<p>You can pass parameters to the filter by providing them as arguments in the attribute declaration.</p>



<p></p>



<p><strong>Example </strong></p>



<p></p>



<pre class="wp-block-preformatted"> <code>[TypeFilter(typeof(CustomFilter), Arguments = new object[] { "id", 123 })]</code>. </pre>



<p></p>



<p>These parameters are then passed to the filter&#8217;s constructor.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-summary">Summary</h2>



<p></p>



<p>ServiceFilter is used to apply filters at the service registration level in the startup class and while TypeFilter is used to apply filters directly to specific classes or methods. </p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>The choice between ServiceFilter and TypeFilter depends on whether you need to apply a filter globally to services/interfaces or selectively to individual classes/methods. </p>



<p></p>



<p>Service filter allows greater reusability and flexibility comapre to TypeFilter.</p>
</blockquote>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/servicefilter-and-typefilter-differences-in-dot-net-csharp/">ServiceFilter and TypeFilter differences in .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/servicefilter-and-typefilter-differences-in-dot-net-csharp/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
