Zuzlx
Zuzlx

Reputation: 1266

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

Upvotes: 3

Views: 767

Answers (1)

enet
enet

Reputation: 45596

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.

Upvotes: 7

Related Questions