What do I learn – System IO, Lazy Programming and Async/Await C# – Week 25

Lately, I made my own compromise to finish reading a blog about C# (that is this one), this week I read the last topic that talks about File Streams and how to read/write bytes. 

It is also important to mention that I started a new book from Safari Books that is called Functional Programming in C#: How to write better C# code by Enrico Buonanno where I read about some topics like async functions and lazy programming. 

Working with files and directories in C#

System.IO.Stream is an abstract class that provides standard methods to transfer bytes (read and write) to the source; it is like a wrapper class. 

The following classes inherit stream to provide the functionality to read/write bytes from a particular source: 

C# provides the following classes to work with the file system.  

They can be used to access directories, access files, open files, create new files or move existing files from one location to another: 

  • File
  • FileInfo
  • Directory
  • DirectoryInfo
  • Path

It is important to mention that the most used and important classes to understand are File & FileInfo: 

File: Use this static File class to perform some quick operations on physical file. 

It is not recommended to use File class for multiple operations on multiple files at the same time due to performance reasons. 

Use FileInfo class in that scenario. 

FileInfo: The FileInfo class provides the same functionality as the static file class, but you have more control on read/write operations on files by writing code manually for reading and writing bytes from a file.

Lazy computation

Laziness in computing means deferring a computation until its result is needed. This is beneficial when the computation is expensive and its result may not be needed. 

Consider the following example of a method that randomly picks one of two given numbers:

The interesting thing to point out here is that when you invoke peek, both expresions are evaluated. 

Even though only one of them is needed at the end. 

Pick now first chooses between the two functions and then evaluates one of them. 

As result, only one computation is performed. 

Working with asynchronous computations

A program may begin some operation that takes a relatively long time, such as requesting data from another application, but it won’t sit idle, waiting for that operation to complete. 

Instead, it will go on to do other work and resume the operation once the data has been received. 

Asynchronous operations are represented in C# using Tasks

Use Task and Task<T> to represent asynchronous operations. 

Use the await keyword to await the task, which frees the current thread to do another work, while the asynchronous operation completes. 


Leave a Reply

Your email address will not be published. Required fields are marked *