상세 컨텐츠

본문 제목

Static Method Using "this" Parameter - C# & .NET

본문

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

 

728x90

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!

 

 

728x90
반응형

관련글 더보기