Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the @function {} block and why do we need it

I'm trying to understand the significance of the @functions {} block in blazor webassembly. If I create a new blazor project in VS it looks like below out of the box. We have a @code block. But then in many blazor docs, I see @functions{}..what is the difference? When should I use which? Can I use them together? Can I nest them together? When I see { and } I think of scope vars and objects. Does scope has to do with it? Why would I want to scope my vars in a razor page? Thanks in advance.

Out of the box template

like image 403
Zuzlx Avatar asked Oct 14 '25 17:10

Zuzlx


1 Answers

At the beginning, the @functions {} block directive which enables adding C# members (fields, properties, and methods) to the generated Blazor class was used. But then Steve Anderson and friends reached the conclusion that a new directive term should replace the @functions {} which is used in Razor Pages as well. After long debate in github, the @code term was chosen.

You should replace the @functions term with the @code term whenever you use old code. This is for consistency' sake only, as the term @functions is supported as well (perhaps for compatibility's sake). In short you can use either of the two without any issues. But one must not be a "smart boy" and use the @functions term so as to impress other how smart they are. The @code term has been successfully adopted by the community and that is how one should code.

One thing is important to remember: Do not use both terms in your Blazor apps. Be consistent.

like image 186
enet Avatar answered Oct 18 '25 02:10

enet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!