top of page

Static Method Using "this" - 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.


 

If you use "this" static method, you will create the following static method. This is a static method that does NOT require an instantiation 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.


 

How would you use this method in real world? Extremely simple as below!


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!

pngegg (11)_result.webp

<Raank:랑크 /> 구독 하기 : Subscribe

감사합니다! : Thanks for submitting!

bottom of page