<?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>CSharp - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/category/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Tue, 03 Oct 2023 20:59:31 +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>CSharp - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>C# .NET MySQL Optimize All Tables &#8211; Guidelines</title>
		<link>https://thecodebuzz.com/csharp-dotnet-core-mysql-get-list-optimize-all-database-tables/</link>
					<comments>https://thecodebuzz.com/csharp-dotnet-core-mysql-get-list-optimize-all-database-tables/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 03 Oct 2022 00:57:00 +0000</pubDate>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[doing recreate + analyze instead]]></category>
		<category><![CDATA[mysql optimize database mysql optimize table after delete]]></category>
		<category><![CDATA[mysql optimize index]]></category>
		<category><![CDATA[MySQL OPTIMIZE table]]></category>
		<category><![CDATA[mysql optimize table innodb]]></category>
		<category><![CDATA[mysql optimize table time estimation]]></category>
		<category><![CDATA[optimize table sql]]></category>
		<category><![CDATA[table does not support optimize]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=23840</guid>

					<description><![CDATA[<p>C#.NET MySQL OPTIMIZE all tables &#8211; Guidelines Today in this article, we will learn about C# .NET MySQL OPTIMIZE all tables. We will also see how to get all tables listed from MySQL and optimize each table programmatically using C#.NET. As a developer or DBA (Database administrator) or tester, it&#8217;s important of validating the schema [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/csharp-dotnet-core-mysql-get-list-optimize-all-database-tables/">C# .NET MySQL Optimize All Tables – Guidelines</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h2 class="wp-block-heading">C#.NET MySQL OPTIMIZE all tables &#8211; Guidelines</h2>



<figure class="wp-block-image size-full"><a href="https://www.thecodebuzz.com/mysql-optimize-all-tables-using-cli-shell-terminal/" target="_blank" rel="noopener"><img fetchpriority="high" decoding="async" width="566" height="302" src="https://www.thecodebuzz.com/wp-content/uploads/2022/10/Get-all-Tables-list-in-MySQL-database-C-net-core.jpg" alt="C# .NET MySQL Optimize All Tables" class="wp-image-23858" srcset="https://thecodebuzz.com/wp-content/uploads/2022/10/Get-all-Tables-list-in-MySQL-database-C-net-core.jpg 566w, https://thecodebuzz.com/wp-content/uploads/2022/10/Get-all-Tables-list-in-MySQL-database-C-net-core-300x160.jpg 300w" sizes="(max-width: 566px) 100vw, 566px" /></a></figure>



<p>Today in this article, we will learn about C# .NET MySQL <strong>OPTIMIZE </strong>all tables. We will also see how to get all tables listed from MySQL and optimize each table programmatically using C#.NET.</p>



<p></p>



<p>As a developer or DBA (Database administrator) or tester, it&#8217;s important of validating the schema your database supports which includes all the tables and their structure. </p>



<p></p>



<p>Today, in this article, we will discuss below aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-getting-started">Getting started</a></li><li><a href="#aioseo-add-nuget-package-mysqlconnector">Add NuGet package &#8211;  MySqlConnector</a></li><li><a href="#aioseo-command">Command</a></li><li><a href="#aioseo-optimizing-the-table-using-c-net-code">Optimizing the table using C# .NET Code</a></li><li><a href="#aioseo-optimizing-all-tables-using-c-net-code">Optimizing All Tables using C# .NET Code</a></li></ul></div>



<p></p>



<p>Getting a list of tables in a database is a most useful query that most developers use.</p>



<p></p>



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



<p></p>



<p>Create any .NET or .NET Core application. To keep it simple I shall be using the Console application however you can use any project template.</p>



<p></p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="221" src="https://www.thecodebuzz.com/wp-content/uploads/2020/09/Connect-SQL-Server-in-Csharp-Example-1024x221.jpg" alt="C# .NET MySQL Optimize " class="wp-image-12432" srcset="https://thecodebuzz.com/wp-content/uploads/2020/09/Connect-SQL-Server-in-Csharp-Example-1024x221.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/09/Connect-SQL-Server-in-Csharp-Example-300x65.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/09/Connect-SQL-Server-in-Csharp-Example-768x166.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/09/Connect-SQL-Server-in-Csharp-Example-1536x332.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/09/Connect-SQL-Server-in-Csharp-Example-785x170.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/09/Connect-SQL-Server-in-Csharp-Example.jpg 2040w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading" id="aioseo-add-nuget-package-mysqlconnector">Add NuGet package &#8211;  MySqlConnector  </h2>



<p></p>



<p>Please install the <em><strong>MySqlConnector</strong></em> Nuget package using Nuget Package Manager,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">PM&gt; NuGet\Install-Package Microsoft.Extensions.Configuration -Version 6.0.1</pre>



<p>And</p>



<pre class="wp-block-preformatted has-medium-font-size">PM&gt; NuGet\Install-Package <a href="https://www.nuget.org/packages/MySqlConnector/2.1.13" target="_blank" rel="noopener" title="">MySqlConnector </a>-Version 2.1.13</pre>



<p></p>



<p>OR using .NET CLI</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">dotnet add package Microsoft.Extensions.Configuration --version 6.0.1</pre>



<p>and </p>



<pre id="dotnet-cli-text" class="wp-block-preformatted has-medium-font-size">dotnet add package MySqlConnector --version 2.1.13</pre>



<p></p>



<p></p>



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



<p></p>



<p>Let us validate the with the most basic command as below. The following query will show all tables in a MySQL database:</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">SHOW TABLES;</pre>



<p></p>



<p>Once you know the table to be optimized, use the below query to optimize the same</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">OPTIMIZE TABLE {table} 
</pre>



<p></p>



<p>If you have multiple tables to be optimized, you can specify the table list as below,</p>



<p></p>



<p class="has-medium-font-size">OPTIMIZE TABLE { table1, table2, table3 }   </p>



<p></p>



<p>Below is a sample C# query supporting the show tables,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">MySqlCommand cmd = new MySqlCommand($"OPTIMIZE TABLE {table}", connection);</pre>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-optimizing-the-table-using-c-net-code">Optimizing the table using C# .NET Code</h2>



<p></p>



<p>Optimizing the given table using C# .NET Code can be achieved as below,</p>



<p></p>



<p>Sample code,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
        try
            {
                connection.ConnectionString = con2;
                connection.Open();
                MySqlCommand cmd = new MySqlCommand($&quot;OPTIMIZE TABLE {table}&quot;, connection);
                    cmd.ExecuteNonQuery();
                }
            }

            catch (Exception ex)
            {
                
            }

            connection.Close();
</pre></div>


<p></p>



<p>Where <strong><em>table </em></strong>is the table name to be optimized.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-optimizing-all-tables-using-c-net-code">Optimizing All Tables using C# .NET Code </h2>



<p></p>



<p>If you&#8217;re interested to optimize all the tables in the given database using C# .NET Code then please see the below code to achieve the same.</p>



<p></p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
try
            {
                connection.ConnectionString = con2;
                connection.Open();
                string cmdStr = &quot;show tables&quot;;
                TableNames = MySqlTableCollections(connection, cmdStr);

                foreach (string table in TableNames)
                {
                    MySqlCommand cmd = new MySqlCommand($&quot;OPTIMIZE TABLE {table}&quot;, connection);
                    cmd.ExecuteNonQuery();
                }
            }

            catch (Exception ex)
            {
                
            }
            connection.Close();

</pre></div>


<p></p>



<p><strong>MySqlTableCollections </strong>method logic is defined as below,</p>



<p></p>



<figure class="wp-block-image size-large"><a href="csharp-dotnet-core-mysql-get-list-optimize-all-database-tables" target="_blank" rel="noopener"><img decoding="async" width="1024" height="340" src="https://www.thecodebuzz.com/wp-content/uploads/2022/11/Get-all-Tables-in-MySQL-database-Csharp-net-core-1024x340.jpg" alt="csharp-dotnet-core-mysql-get-list-optimize-all-database-tables" class="wp-image-23926" srcset="https://thecodebuzz.com/wp-content/uploads/2022/11/Get-all-Tables-in-MySQL-database-Csharp-net-core-1024x340.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2022/11/Get-all-Tables-in-MySQL-database-Csharp-net-core-300x100.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/11/Get-all-Tables-in-MySQL-database-Csharp-net-core-768x255.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/11/Get-all-Tables-in-MySQL-database-Csharp-net-core-785x261.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2022/11/Get-all-Tables-in-MySQL-database-Csharp-net-core.jpg 1513w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



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



<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>The post <a href="https://thecodebuzz.com/csharp-dotnet-core-mysql-get-list-optimize-all-database-tables/">C# .NET MySQL Optimize All Tables – Guidelines</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/csharp-dotnet-core-mysql-get-list-optimize-all-database-tables/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to File Lock and Unlock in C# .NET</title>
		<link>https://thecodebuzz.com/file-lock-unlock-read-write-file-c-sharp-thread-safe-net-core/</link>
					<comments>https://thecodebuzz.com/file-lock-unlock-read-write-file-c-sharp-thread-safe-net-core/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 12 Mar 2022 03:26:20 +0000</pubDate>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[C# lock file read]]></category>
		<category><![CDATA[C# lock file write]]></category>
		<category><![CDATA[write file lock c# .net]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=21154</guid>

					<description><![CDATA[<p>File Lock and Unlock in C# .NET Today in this article we shall see the simple and easy approach of How to perform File Lock and Unlock in C# .NET when using it for reading or writing aka performing an update. The discussed approach is very useful while dealing with any size of the file [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/file-lock-unlock-read-write-file-c-sharp-thread-safe-net-core/">How to File Lock and Unlock in C# .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">File Lock and Unlock in C# .NET</h1>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="765" height="420" src="https://www.thecodebuzz.com/wp-content/uploads/2022/03/Read-a-Large-File-in-Chunks-in-C.jpg" alt="File Lock and Unlock in C#, How to lock file" class="wp-image-21148" srcset="https://thecodebuzz.com/wp-content/uploads/2022/03/Read-a-Large-File-in-Chunks-in-C.jpg 765w, https://thecodebuzz.com/wp-content/uploads/2022/03/Read-a-Large-File-in-Chunks-in-C-300x165.jpg 300w" sizes="auto, (max-width: 765px) 100vw, 765px" /></figure>



<p>Today in this article we shall see the simple and easy approach of How to perform File Lock and Unlock in C# .NET when using it for reading or writing aka performing an update. </p>



<p></p>



<p>The discussed approach is very useful while dealing with any size of the file (<strong><em>.TXT or .CSV or .XLSX</em></strong>) where you need a temporary lock on a file so that other resources can not use it. This could be a legitimate use case for many requirements. It&#8217;s also important to write to file in a thread-safe manner.</p>



<p></p>



<p>In this article, we will cover when there is a need to lock files at the time of reading the data and when writing the data to a file.</p>



<p>Today in this article, we will cover below aspects,</p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-lock-a-file-while-reading-the-file-data---approach-1">Lock a file while reading the file data &#8211; Approach 1</a></li><li><a href="#aioseo-lock-a-file-while-reading-writing-the-file-data---approach-2">Lock a file while Reading/Writing the file data &#8211;  Approach 2</a></li><li><a href="#aioseo-lock-a-file-while-writing-to-file-data---thread-safety---approach-3">Lock a file while Writing to File data &#8211; Thread safety &#8211; Approach 3</a></li></ul></div>



<p></p>



<p>For demonstration purposes, I have used a very simple example here.</p>



<p></p>



<p>Let&#8217;s say I have a Text file that I am creating using some process. I want this file to be locked until the file generation is completed is done.</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2021/05/read-a-very-large-file-by-chunks-not-line-by-line-1024x276.jpg" alt="lock file in C# , lock file writing c#, write to file in a thread-safe manner." class="wp-image-15752" width="562" height="151" srcset="https://thecodebuzz.com/wp-content/uploads/2021/05/read-a-very-large-file-by-chunks-not-line-by-line-1024x276.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/05/read-a-very-large-file-by-chunks-not-line-by-line-300x81.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/05/read-a-very-large-file-by-chunks-not-line-by-line-768x207.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/05/read-a-very-large-file-by-chunks-not-line-by-line-1536x414.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2021/05/read-a-very-large-file-by-chunks-not-line-by-line-785x212.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2021/05/read-a-very-large-file-by-chunks-not-line-by-line.jpg 2029w" sizes="auto, (max-width: 562px) 100vw, 562px" /></figure>



<p></p>



<p>Below is simple logic which reads the file.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-lock-a-file-while-reading-the-file-data---approach-1">Lock a file while reading the file data &#8211; Approach 1 </h2>



<p></p>



<p>If you would lock a file while reading a file then it is pretty simple to open a file and perform read operations using the below code as explained.</p>



<p></p>



<p>In the below code, we are reading the file using the <strong><em>FileStream </em></strong>Open method which lets you open FileStream on the specified path, with the specified mode.</p>



<p></p>



<p>Setting up<strong><em> FileShare.None</em></strong> will perform below,</p>



<p></p>



<ul class="wp-block-list">
<li>Declines sharing of the current file. </li>



<li>Any request to open the file will fail until the file is closed.</li>
</ul>



<p></p>



<p>Let&#8217;s see below complete example,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [7]; title: ; notranslate">
 private static void ReadFile(string filePath)
        {
            const int MAX_BUFFER = 1048576; //1MB 
            byte&#x5B;] buffer = new byte&#x5B;MAX_BUFFER];
            int bytesRead;
            int noOfFiles = 0;
            using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
            using (BufferedStream bs = new BufferedStream(fs))
            {
                while ((bytesRead = bs.Read(buffer, 0, MAX_BUFFER)) != 0) //reading 1mb chunks at a time
                {
                    noOfFiles++;
                    //Let&#039;s create a small size file using the data. Or Pass this data for any further processing.

                    File.WriteAllBytes($&quot;Test{noOfFiles}.txt&quot;, buffer);
                }
            }
        }

</pre></div>


<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-lock-a-file-while-reading-writing-the-file-data---approach-2">Lock a file while Reading/Writing the file data &#8211;  Approach 2  </h2>



<p></p>



<p>Lock a file in C# using File.Lock() method . The lock method let you lock a file so another process cannot access the file. This works even if it has <strong><em>read/write</em></strong> access to the file.</p>



<p></p>



<p>You can lock a file while reading the below simple code,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [3]; title: ; notranslate">
//Good
using (FileStream stream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                stream.Lock(0, stream.Length);

                /// You logic here////
            }
</pre></div>


<p></p>



<p>In the above method, we can call <em><strong>File.Open </strong></em>to deal a file for reading or writing operations. </p>



<p></p>



<p>Here we are exclusively locking out other processes or threads from accessing the file while you are using it.</p>



<p></p>



<p>When you are done with your operations on the file, code goes out of &#8220;using&#8221; statements thereby closing any file handle open and releasing it for others to use your file.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-lock-a-file-while-writing-to-file-data---thread-safety---approach-3">Lock a file while Writing to File data &#8211; Thread safety &#8211; Approach 3 </h2>



<p></p>



<p>If you ever need to lock a file while writing the data, you can use the below logic to perform the same. </p>



<p></p>



<p>Below we are maintaining <strong><em>synchronization </em></strong>on the file using the <em><strong>lock</strong></em>.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
 public class WiteToFileUsingLock
    {
        public string Filepath { get; set; }
        private static object lockerFile = new Object();

        public void WriteToFile(StringBuilder text)
        {
            lock (lockerFile)
            {
                using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read))
                using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))
                {
                    writer.Write(text.ToString());
                }
            }

        }
    }
</pre></div>


<p></p>



<p>Above <strong><em>Lock </em></strong>exclusively locks the section of code dealing with files until the stream is written to a file and closed.  </p>



<p></p>



<p><strong>References</strong>: </p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/find-most-recent-files-in-directory-in-c-net/" target="_blank" rel="noreferrer noopener" title="Find Most Recent Files in Directory in C#.NET"><em>Find Most Recent Files in Directory in C#.NET</em></a></li>
</ul>



<p></p>



<p>That&#8217;s all! Happy coding!</p>



<p></p>



<p>Does this help you fix your issue? </p>



<p></p>



<p>Do you have any better solutions or suggestions? Please sound off your comments below.</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/file-lock-unlock-read-write-file-c-sharp-thread-safe-net-core/">How to File Lock and Unlock in C# .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/file-lock-unlock-read-write-file-c-sharp-thread-safe-net-core/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Covariance and Contravariance in C# .NET</title>
		<link>https://thecodebuzz.com/covariance-and-contravariance-in-csharp-dot-net/</link>
					<comments>https://thecodebuzz.com/covariance-and-contravariance-in-csharp-dot-net/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 03 Mar 2022 16:53:00 +0000</pubDate>
				<category><![CDATA[CSharp]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=15166</guid>

					<description><![CDATA[<p>Covariance and Contravariance in C# .NET Today in this article, we will learn the concept of Covariance and Contravariance in C# .NET. Covariant and contravariant generic type parameters provide flexibility in assigning and using the types. For example, covariant-type parameters enable you to make assignments that look much like ordinary polymorphism. This defined relationship affects [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/covariance-and-contravariance-in-csharp-dot-net/">Covariance and Contravariance in C# .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Covariance and Contravariance in C# .NET</h1>



<p>Today in this article, we will learn the concept of Covariance and Contravariance in C# .NET.</p>



<p>Covariant and contravariant generic type parameters provide flexibility in assigning and using the types. For example, covariant-type parameters enable you to make assignments that look much like ordinary polymorphism. This defined relationship affects the code compilation and ultimately runtime resolution of our types.</p>



<p></p>



<p>Before we dive into the concept of Covariance and Contravariance,  Let&#8217;s dive into what we already know about the basic OOPS concept. As we know with the OOPS concept C# already has a relationship defined for the object in the form of <em style="font-weight: bold;">Inheritance</em>, <em><strong>Polymorphism,</strong></em> and <em><strong>subtyping</strong></em>.</p>



<p>Today in this article, we will cover below aspects,</p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-natural-oops-principles---a-reminder-for-complex-type">Natural OOPS principles &#8211; a Reminder for Complex type</a></li><li><a href="#aioseo-covariance-in-array">Covariance in Array</a></li><li><a href="#aioseo-covariance-and-contravariance-in-generics">Covariance and Contravariance  in Generics</a></li><li><a href="#aioseo-covariance-and-contravariance-in-generics-delegates">Covariance and Contravariance  in Generics Delegates</a></li></ul></div>



<p></p>



<h2 class="wp-block-heading" id="aioseo-natural-oops-principles---a-reminder-for-complex-type">Natural OOPS principles &#8211; a Reminder for Complex type</h2>



<p></p>



<p>Let&#8217;s try rewinding OOPS &#8211; <strong><em>Inheritance</em></strong> and <strong>Subtyping</strong>.</p>



<p></p>



<p>Let&#8217;s take a simple example as shown below,</p>



<p></p>



<pre class="wp-block-preformatted">public class Employee{ }


public class FullTimeEmployee: Employee{ }


public class ContractEmployee: Employee{ }
</pre>



<p></p>



<p>Let&#8217;s understand the above example:</p>



<p></p>



<ul class="wp-block-list"><li><strong><em>Inheritance </em></strong>&#8211; FullTimeEmployee and&nbsp;<strong>ContractEmployee</strong><strong> </strong>inherit from&nbsp;the base class Employee.</li><li><strong><em>Subtyping </em></strong>&#8211; One can easily substitute&nbsp;<strong>Employee</strong><strong> </strong>with&nbsp;<strong>FullTimeEmployee</strong><strong> </strong>or&nbsp;<strong><em>ContractEmployee</em></strong><strong><em> </em></strong>using subtyping principles. That means you are allowed to do the below,<ul><li>If a method has an input parameter of the type&nbsp;Employee, you can pass an instance of&nbsp;ContractEmployee or&nbsp;FullTimeEmployee as input</li><li>If a method is declared to return an&nbsp;Employee, you can return a&nbsp;ContractEmployee or a&nbsp;FullTimeEmployee.</li><li>A subclass&nbsp;overrides a method in a base class, the compiler must check that the overriding method has the right type.</li></ul></li></ul>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-covariance-in-array"><strong>Covariance in Array</strong></h2>



<p></p>



<p>Let&#8217;s start by looking at what&nbsp;<em>covariance</em>&nbsp;means.</p>



<p>Let&#8217;s take an example of an <strong><em>Employee </em></strong>class above discussed using Arrays.</p>



<p>In <strong>C#</strong>&nbsp;(and&nbsp;<strong>. NET</strong>), variance is a relation between a type. If two types&nbsp;are given as <strong>Base</strong>&nbsp;and&nbsp;<strong>Derived</strong> then,</p>



<p></p>



<ul class="wp-block-list"><li>The relationship can be defined between <strong>Base</strong>&nbsp;and&nbsp;<strong>Derived</strong></li><li>And base class remains higher on the relationship <strong>Base&nbsp;≥</strong>&nbsp;<strong>Derived</strong></li></ul>



<p></p>



<p>Let&#8217;s take the above example into consideration,</p>



<ul class="wp-block-list"><li><strong><em>Covariance </em></strong>relationship: <strong><em>FullTimeEmployee[] </em></strong>is an<strong><em> Employee[]</em></strong></li></ul>



<p>Here <strong>Employee</strong>[] <strong>≥ <em>FullTimeEmployee</em></strong>[]</p>



<p>So it defines the Covariance in Employee if the order of constructed type i.e <strong><em>FullTimeEmployee</em></strong> follows the order<strong><em> Base &gt;Derived</em></strong></p>



<ul class="wp-block-list"><li><strong><em>Contravariant </em></strong>relationship:<strong><em>Employee[] is FullTimeEmployee[]</em></strong></li></ul>



<p></p>



<p></p>



<p>Here it defines Contravariance as the order is reversed,</p>



<p>Here <strong>Employee</strong>[] &lt;= <strong><em>FullTimeEmployee</em></strong>[]</p>



<p>So it defines the ContraCovariance in Employee if the order of constructed type i.e <strong><em>FullTimeEmployee</em></strong>.</p>



<p></p>



<p></p>



<ul class="wp-block-list"><li>Invariant relationship : <strong><em>Employee[] </em></strong>is not <strong><em>FullTimeEmployee[] </em></strong><em>and <strong>FullTimeEmployee[] </strong></em>is not <em>an<strong> Employee[]</strong></em></li></ul>



<p>Let&#8217;s now see how these defined relationships affect the code compilation and ultimately runtime resolution of our types.</p>



<p></p>



<p>In the above-explained relationship <strong><em>Covariance </em></strong>and <strong><em>Contravariant </em></strong>relationship is not <strong><em>type-safe.</em></strong> This unsafe behavior can be verified using the below code,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
           //checking is an array of FullTimeEmployee

            FullTimeEmployee&#x5B;] checking = { new FullTimeEmployee(&quot;001&quot;) };

            //accountCollection array of CheckingAccounts

            Employee&#x5B;] accountCollection = checking;

            //Now accountCollection here is an Array of 
            //FullTimeEmployee but not safe as assigning 
            //ContractEmployee could result in exception 

            accountCollection&#x5B;0] = new ContractEmployee(&quot;001&quot;);

</pre></div>


<p></p>



<p>In the above example, <strong><em>accountCollection </em></strong>is the collection of <strong><em>FullTimeEmployee</em></strong>. Being able to use FullTimeEmployee or ContractEmployee where Employee is expected shows that Arrays are <strong><em>Covariant.</em></strong></p>



<p></p>



<p>Later <strong><em>accountCollection </em></strong>is assigned with ContractEmployee which compiles perfectly fine but results in an exception in the runtime. These two types are incompatible the assignment doesn&#8217;t work and throws the below error as expected.</p>



<p></p>



<p>&#8220;Attempted to access an element as a type incompatible with the array&#8221;</p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="321" src="https://www.thecodebuzz.com/wp-content/uploads/2021/03/Covariance-and-Contravariance-in-C-.NET_-1024x321.jpg" alt="Covariance and Contravariance in C# .NET" class="wp-image-15213" srcset="https://thecodebuzz.com/wp-content/uploads/2021/03/Covariance-and-Contravariance-in-C-.NET_-1024x321.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/03/Covariance-and-Contravariance-in-C-.NET_-300x94.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/03/Covariance-and-Contravariance-in-C-.NET_-768x241.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/03/Covariance-and-Contravariance-in-C-.NET_-1536x482.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2021/03/Covariance-and-Contravariance-in-C-.NET_-785x246.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2021/03/Covariance-and-Contravariance-in-C-.NET_.jpg 1741w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p>The above behavior can also be explained using the below simple example </p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
            //fullTime is an array of FullTimeEmployee

            FullTimeEmployee&#x5B;] fullTime = { new FullTimeEmployee(&quot;001&quot;) };

            //accountCollection array of FullTimeEmployees

            Employee&#x5B;] accountCollection = fullTime;

            //Now accountCollection here is an Array of 
            //FullTimeEmployee but not safe as assigning 
            //ContractEmployee could result in exception 

            accountCollection&#x5B;0] = new ContractEmployee(&quot;001&quot;);

</pre></div>


<p></p>



<p>In the above example, we get the same exception of <em><strong>ArrayTypeMisMatchException</strong></em>. there is always a type check to verify the runtime type of the definition of the elements of the array is greater or equal to the instance being assigned to the element. </p>



<p>In the above example, because the runtime type of the array is&nbsp;an <strong>array of strings</strong>, the first assignment of array elements is valid because&nbsp;string ≥&nbsp;string&nbsp;and the second is invalid because&nbsp;<strong>string ≤</strong>&nbsp;<strong>object</strong>.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-covariance-and-contravariance-in-generics">Covariance and Contravariance&nbsp; in Generics  </h2>



<p></p>



<p>Covariant and contravariant generics provide greater flexibility in assigning and using generic types. The Base type and Derived type relationship defined above already holds true for generics also.</p>



<p></p>



<p>The type parameter of the&nbsp;IEnumerable&lt;T&gt;&nbsp;interface is covariant. You can assign an instance of <strong><em>IEnumerable&lt;Derived&gt;</em></strong> to a variable of type <em><strong>IEnumerable&lt;Base&gt;</strong></em>.</p>



<p></p>



<p><strong>Covariance</strong>&nbsp;in  generic type implemented is using the&nbsp;<em>out </em>generic modifier:</p>



<p>A generic type definition&nbsp;<strong>Generic&lt;T&gt;</strong>&nbsp;is:</p>



<p></p>



<ul class="wp-block-list"><li><strong>Covariant </strong>in<strong> T</strong>&nbsp;if the relationship is defined as <strong>Generic&lt;Base&gt; ≥ Generic&lt;Derived&gt;</strong>.</li><li><strong>Contravariant </strong>in <strong>T</strong>&nbsp;if the ordering of the constructed types are reversed from the ordering of the generic type parameters:&nbsp;<strong>Generic&lt;Base&gt; ≤ Generic&lt;Derived&gt;</strong>.</li><li><strong>Invariant </strong>in<strong> T</strong>&nbsp;if neither of the above applies.</li></ul>



<p></p>



<p>Below are a few rules for Covariance,</p>



<p></p>



<ul class="wp-block-list"><li>A covariant type parameter can be used as the return type of a delegate, and contravariant type parameters can be used as parameter types. </li></ul>



<ul class="wp-block-list"><li>For an interface, covariant-type parameters can be used as the return types of the interface&#8217;s methods, and contravariant-type parameters can be used as the parameter types of the interface&#8217;s methods.</li></ul>



<ul class="wp-block-list"><li>A generic interface or generic delegate type can have both covariant and contravariant type parameters.</li></ul>



<p></p>



<p>Starting with the .NET Framework&nbsp;4,&nbsp;several other generic interfaces have covariant type parameters; </p>



<p></p>



<ul class="wp-block-list"><li>&nbsp;<a href="https://msdn.microsoft.com/en-us/library/bb351562(v=vs.100)" target="_blank" rel="noreferrer noopener">IQueryable&lt;T&gt;</a></li></ul>



<ul class="wp-block-list"><li><a href="https://msdn.microsoft.com/en-us/library/bb344977(v=vs.100)" target="_blank" rel="noreferrer noopener">IGrouping&lt;TKey, TElement&gt;</a>.&nbsp;</li></ul>



<p></p>



<p>All the type parameters of these interfaces are covariant, so the type parameters are used only for the return types of the members.&nbsp;</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
public interface IEnumerable&amp;lt;out T&gt;
{
    IEnumerator&amp;lt;T&gt; GetEnumerator();
}

public interface IEnumerator&amp;lt;out T&gt;
{
    T Current { get; }
    bool MoveNext();
}
</pre></div>


<p></p>



<p>Please note the <strong><em>IEnumerable&nbsp;</em></strong>interface is marked as&nbsp;<strong><em>covariant</em>&nbsp;</strong>using the&nbsp;<strong><code>out</code>&nbsp;</strong>annotation.</p>



<p></p>



<p></p>



<p><strong>Contravariance</strong>&nbsp;is enforced in relation to a particular generic type  using the&nbsp;<b><i>in-generic</i></b> modifier,</p>



<p></p>



<p>.NET Framework&nbsp;4+ onwards,&nbsp;several other generic interfaces have contravariant type parameters; for example:&nbsp;</p>



<p></p>



<ul class="wp-block-list"><li><a href="https://msdn.microsoft.com/en-us/library/8ehhxeaf(v=vs.100)" target="_blank" rel="noreferrer noopener">IComparer&lt;T&gt;,&nbsp;IComparable&lt;T&gt;</a></li><li><a href="https://msdn.microsoft.com/en-us/library/8ehhxeaf(v=vs.100)" target="_blank" rel="noreferrer noopener">IEqualityComparer&lt;T&gt;</a></li></ul>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
public interface IComparer&amp;lt;in T&gt;
{
    int Compare(T x, T y);
}
</pre></div>


<p></p>



<p>These interfaces have only contravariant type parameters, so in the members of the interfaces, the type parameters are used only as parameter types.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-covariance-and-contravariance-in-generics-delegates">Covariance and Contravariance&nbsp; in Generics Delegates</h2>



<p></p>



<p>.NET Framework&nbsp;4+ onwards,&nbsp;the Func generic delegates are defined as below,</p>



<p></p>



<ul class="wp-block-list"><li><a href="https://msdn.microsoft.com/en-us/library/bb549151(v=vs.100)">Func&lt;T, TResult&gt;</a>&#8211;  have <strong><em>covariant return types </em></strong>and <strong><em>contravariant parameter types</em></strong>. </li><li><a href="https://msdn.microsoft.com/en-us/library/bb549311(v=vs.100)">Action&lt;T1, T2&gt;</a>&#8211; The Action generic delegates, have<strong><em> contravariant parameter types. </em></strong></li></ul>



<p></p>



<p>The above indicates that delegates can be assigned to variables that have more derived parameter types and (in the case of the Func generic delegates) less derived return types.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
class Employee { }

    class FullTimeEmployee : Employee { }

    class Program
    {
        
        public delegate Employee HandlerMethod();

        public static Employee AccountHandler()
        {
            return null;
        }

        public static FullTimeEmployee CheckinghHandler()
        {
            return null;
        }

        static void CovarianceTest()
        {
            HandlerMethod handlerMammals = AccountHandler;

            // Covariance is valid here for below assignment 
            HandlerMethod handlerDogs = CheckinghHandler;
        }
    }

</pre></div>


<p></p>



<p><strong><em>Example Contravariance:</em></strong></p>



<p></p>



<p>In the below example, we shall see with contravariance, you can use one event handler instead of separate handlers and demonstrate delegate&#8217;s use with methods that have parameters (whose types are base type of delegate signature parameters).</p>



<p></p>



<pre class="wp-block-preformatted">public delegate void KeyEventHandler(object sender, KeyEventArgs e)</pre>



<p></p>



<pre class="wp-block-preformatted">public delegate void MouseEventHandler(object sender, MouseEventArgs e)</pre>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // Use a method that has an EventArgs (Although the event expects the KeyEventArgs).  
            this.button1.KeyDown += this.MultiHandler;

            // Use the same method expects the MouseEventArgs parameter.  
            this.button1.MouseClick += this.MultiHandler;
        }

        // Event handler that accepts a parameter of the EventArgs type.  
        private void MultiHandler(object sender, System.EventArgs e)
        {
            label1.Text = System.DateTime.Now.ToString();
        }
    }

</pre></div>


<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>The post <a href="https://thecodebuzz.com/covariance-and-contravariance-in-csharp-dot-net/">Covariance and Contravariance in C# .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/covariance-and-contravariance-in-csharp-dot-net/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Get File&#8217;s Last Modified or Last Written date in C#</title>
		<link>https://thecodebuzz.com/get-files-last-modified-date-or-last-written-date-in-csharp-netcore/</link>
					<comments>https://thecodebuzz.com/get-files-last-modified-date-or-last-written-date-in-csharp-netcore/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 05 Sep 2021 03:28:00 +0000</pubDate>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[.net core get file last modified date]]></category>
		<category><![CDATA[c# get file creation date]]></category>
		<category><![CDATA[c# get file information]]></category>
		<category><![CDATA[c# get file modified user]]></category>
		<category><![CDATA[c# get last modified date of file]]></category>
		<category><![CDATA[c# get latest file from directory]]></category>
		<category><![CDATA[get file creation date bash]]></category>
		<category><![CDATA[get last modified file from directory c#]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=18956</guid>

					<description><![CDATA[<p>Get File&#8217;s Last Modified or Last Written date in C# Today in this article, we shall see how to get File&#8217;s Last Modified or Last Written date in C# application code. Today in this article, we will cover below aspects, Get Files last Modified date or Last Written date DateTime modifyTime = File.GetLastWriteTime(@"file-input-thecodebuzz.txt"); Get Files [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/get-files-last-modified-date-or-last-written-date-in-csharp-netcore/">Get File’s Last Modified or Last Written date in C#</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Get File&#8217;s Last Modified or Last Written date in C#</h1>



<p>Today in this article, we shall see how to get File&#8217;s Last Modified or Last Written date in C# application code.</p>



<p>Today in this article, we will cover below aspects,</p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-file-getlastwritetime-returns-1601">File GetLastWriteTime returns 1601</a><ul><li><a href="#exceptions">Exceptions</a></li></ul></li></ul></div>



<p><strong>Get Files last Modified date or Last Written date</strong></p>



<p></p>



<pre class="wp-block-preformatted"><code>    DateTime modifyTime = File.GetLastWriteTime(@"file-input-thecodebuzz.txt");</code>
</pre>



<p></p>



<p><strong>Get Files created Date date</strong></p>



<p></p>



<pre class="wp-block-preformatted"><code>    DateTime creationTime= File.GetCreationTime(@"file-input-thecodebuzz.txt");</code>

</pre>



<p>As per Microsoft gudelines,</p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>This method may return an inaccurate value, because it uses native functions whose values may not be continuously updated by the operating system. Each operating system manages the last write time according to its own rules. To improve performance, an operating system might not set the last write time value to the exact time of the last write operation, but might set it to a close approximation instead.</p></blockquote>



<p></p>



<h2 class="wp-block-heading" id="aioseo-file-getlastwritetime-returns-1601">File GetLastWriteTime returns 1601</h2>



<p></p>



<p>This method returns  January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC) if the specified file doesn&#8217;t exist in the specified path.</p>



<p></p>



<h4 class="wp-block-heading" id="exceptions">Exceptions</h4>



<p></p>



<p>You can handle any of the below exceptions, </p>



<p></p>



<ul class="wp-block-list"><li><strong><em>UnauthorizedAccessException</em></strong></li><li><strong><em>ArgumentException</em></strong></li><li><strong><em>PathTooLongException</em></strong></li><li><strong><em>NotSupportedException</em></strong></li></ul>



<p></p>



<p><strong><em>References:  </em></strong></p>



<ul class="wp-block-list"><li><strong><em><a href="https://www.thecodebuzz.com/unit-test-mock-file-methods-csharp-netcore-design/" target="_blank" rel="noreferrer noopener" title="Unit Test and Mock File methods – Guidelines">Unit Test and Mock File methods – Guidelines</a></em></strong></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>The post <a href="https://thecodebuzz.com/get-files-last-modified-date-or-last-written-date-in-csharp-netcore/">Get File’s Last Modified or Last Written date in C#</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/get-files-last-modified-date-or-last-written-date-in-csharp-netcore/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Returning Boolean Task from a Task</title>
		<link>https://thecodebuzz.com/returning-bool-task-from-task-true-false-async-sync/</link>
					<comments>https://thecodebuzz.com/returning-bool-task-from-task-true-false-async-sync/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 02 Sep 2021 18:05:00 +0000</pubDate>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[async task<bool return value]]></category>
		<category><![CDATA[await bool c#]]></category>
		<category><![CDATA[c# task return value]]></category>
		<category><![CDATA[convert task to bool]]></category>
		<category><![CDATA[convert task<bool&#039; to bool c#]]></category>
		<category><![CDATA[how to return task<bool in c#]]></category>
		<category><![CDATA[operator cannot be applied to operands of type task<bool]]></category>
		<category><![CDATA[return task<bool async c#]]></category>
		<category><![CDATA[Returning Boolean Task from a Task]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=18581</guid>

					<description><![CDATA[<p>Returning Boolean Task from a Task Today in this article, we shall see returning Boolean Task from a Task-based method. Here we will return bool from task i.e true or false from task-based operation. Today in this article, we will cover below aspects, Using Task&#60;TResult&#62;&#160; you can return boolean, int, or string depending on your [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/returning-bool-task-from-task-true-false-async-sync/">Returning Boolean Task<bool> from a Task</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Returning Boolean Task from a Task</h1>



<p>Today in this article, we shall see returning Boolean Task from a Task-based method. Here we will return bool from task i.e true or false from task-based operation.</p>



<p>Today in this article, we will cover below aspects,</p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-return-boolean-from-task-asynchronously">Return Boolean from Task Asynchronously</a></li><li><a href="#aioseo-return-bool-true-or-false-from-task-synchronously">Return Bool (True or False) from Task Synchronously</a></li></ul></div>



<p>Using <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1">Task&lt;TResult&gt;</a>&nbsp; you can return boolean, int, or string depending on your requirements where the operand is&nbsp;<code><strong><em>TResult</em></strong></code>. Here declaration must specify a return type of&nbsp;<code>Task&lt;bool&gt;</code> or <code>Task&lt;int&gt;</code> as required.</p>



<p></p>



<p>Async methods that don&#8217;t contain a&nbsp;<code>return</code>&nbsp;<code>statement usually <em>have</em></code> a return type of&nbsp;Task. If a method returns Task, that means it&#8217;s the asynchronous version of a&nbsp;<em><strong><code>void</code>&nbsp;</strong></em>method.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-return-boolean-from-task-asynchronously">Return Boolean from Task Asynchronously </h2>



<p></p>



<p>Below an example for returning a boolean from Task asynchronously.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
public async Task&lt;bool&gt; Delete(string key)
        {
            var isSuccess = false;
            try
            {
               await _cache.RemoveAsync(key);
                isSuccess = true;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                return isSuccess;
            }

            return true;
        }
</pre></div>


<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-return-bool-true-or-false-from-task-synchronously">Return Bool (True or False) from Task Synchronously</h2>



<p></p>



<p>To return Boolean from Task Synchronously, we can use <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1?view=net-5.0">Task.FromResult&lt;TResult&gt;(TResult) Method</a>. This method creates a&nbsp;Task result that&#8217;s completed successfully with the specified result.</p>



<p></p>



<p>The calling method uses an&nbsp;<strong><em>await</em></strong>&nbsp;operator to suspend the caller&#8217;s completion till called async method has finished successfully.</p>



<p></p>



<p>Example</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
public Task&lt;bool&gt; DeleteCache(string key)
        {
            var isSuccess = false;
            try
            {
                 _cache.Remove(key);
                isSuccess = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return Task.FromResult(isSuccess);
            }

            return Task.FromResult(isSuccess); ;
        }
</pre></div>


<p></p>



<p>Here above you determine when to send true or false using Task.FromResult() for the operation based on the custom validation.</p>



<p></p>



<p><strong>References : </strong></p>



<ul class="wp-block-list"><li><a href="https://www.thecodebuzz.com/understanding-async-and-await-api-asynchronous-programming/" title="Multithreading Async and Await methods- Asynchronous Programming" target="_blank" rel="noreferrer noopener"><strong><em>Multithreading Async and Await methods- Asynchronous Programming</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>



<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/returning-bool-task-from-task-true-false-async-sync/">Returning Boolean Task<bool> from a Task</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/returning-bool-task-from-task-true-false-async-sync/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
