Why Use Nested Subroutines in VB.Net?

May 22, 2025 4 answers
Asked by 8mm sprocket
I came across some code using nested subroutines in VB.Net and I'm curious about their purpose. Here's the specific example: when a button is clicked, a new form is created, and a subroutine named `anim` is defined to handle the animation for that form when it shows. But I'm asking, why not just write the animation code directly or define `anim` separately and call it instead? What are the benefits of keeping it nested?

Answers

borrowed.tool
Not to mention, having it nested keeps the related code together, which can be easier to read and manage. However, I know some people find VB a bit outdated and confusing for modern development.
Reply to this answer
Bungler
Nested functions are great for encapsulation. When you define a subroutine inside another, like the `anim` sub in your example, it's only accessible within that outer subroutine. This prevents name collisions in the global namespace, which can get messy, especially in larger projects.
Reply to this answer
+potluck signup
The `anim` subroutine acts as a callback that's triggered only when the form is shown. This is perfect for animations because you want to ensure the form is fully loaded and displayed before executing the animation, making it more efficient.
Reply to this answer
quiche crust
Yeah, I feel like VB should've been left in the past! But if you know how to make it work, it can handle things like API calls just fine. Just... donโ€™t make it your first choice.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions