This is one of my favorite coding method. If used properly, it can make your coding life much easier.
Using "this", you can create a static method. For example, if you frequently use code to convert from byte type to file type, you can create your own static method for the byte type, called "ToFile()". Then you will just call the method by adding ".ToFile()" at the end of a byte type variable.
I will show you a detailed example using the example case above.
If you do not use the custom static method for the byte type, you will always have to create the following function and call it all the time.
public async Task WriteToFileAsync(byte[] bytes, string filePath, string fileName)
{
string destFullName = Path.Combine(filePath, fileName);
// REMOVE, IF A DUPLICATE FILE EXISTS
if (File.Exists(destFullName))
File.Delete(destFullName);
await using FileStream fs =
new FileStream(
destFullName,
FileMode.CreateNew,
FileAccess.Write);
await fs.WriteAsync(bytes, 0, bytes.Length);
return;
}
If you use "this" static method, you will create the following static method. This is a static method that does NOT require an instatiation because it is attached to the instantiated variable. What is the difference between the function above and the one below? First, you are defining "static" method. Second, "this" will be added to the type that needs to be attached, "bytes" parameter in this case.
public static async Task WriteToFileAsync(this byte[] bytes, string filePath, string fileName)
{
string destFullName = Path.Combine(filePath, fileName);
// REMOVE, IF A DUPLICATE FILE EXISTS
if (File.Exists(destFullName))
File.Delete(destFullName);
await using FileStream fs =
new FileStream(
destFullName,
FileMode.CreateNew,
FileAccess.Write);
await fs.WriteAsync(bytes, 0, bytes.Length);
return;
}
How would you use this method in real world? Extremely simple as below!
byte[] imageBytes = GetImageFromDatabase();
string filePath = @"C:\path\";
string fileName = "image.jpeg";
await imageBytes.WriteToFileAsync(filePath, fileName);
Why is this better than a function? Well, it is more readable. You see that the "imageBytes" variable has a method that will convert from the byte array type to the file type. Therefore, this will be easier for debugging in the future as well as code reviews.
This example was a simple case, but if you can utilize this technique wisely, it will help boost your productivity.
Thank you for visiting this page!
Entity Framework Core - Best Practices - C# & .NET (0) | 2023.03.15 |
---|---|
Page Change Event Code That Works in ALL Devices and Browsers - JavaScript (0) | 2023.03.13 |
Easily Create a Modal Dialog Box with Callbacks - JavaScript (0) | 2023.03.01 |
Easy Guide to AutoMapper (Simple Class Converter) - C# & .NET (0) | 2023.02.26 |
Tips for Performance Improvement - Visual Studio (0) | 2023.02.26 |