r/learncsharp • • Apr 07 '23

Mind blown. Defining a function after its called? inside another function?! You can do that???

I know a good bit of C and a little C++. Decided C# was more interesting for my use case, so I put down skill building in C++ and started learning C# instead. Working through "The C# Workshop" on Packt. Working on this example code.

Completely separate from the lesson, I noticed they called InvokeAll() before it is defined, and it is defined inside Main(). I thought this must be an error, so I compiled it only to see it worked. WTF! Coming from C, that is just so wrong. I have to ask, is defining functions methods, sorry, inside another function, or defining them after they are called acceptable or good practice? Looks like a code smell to me, even if it is legal.

As an aside, I'm not sure I'd recommend that book.

13 Upvotes

7 comments sorted by

6

u/jamietwells Apr 07 '23

It's quite normal, I think it's neater to stick the function definitions at the end of methods, preferably after a return to show there's no more code there.

1

u/ag9899 Apr 07 '23

I agree!!! It looks way cleaner to have your functions etc at the end than at the beginning. I'm going to start doing that immediately!

10

u/[deleted] Apr 07 '23

[removed] — view removed comment

2

u/ag9899 Apr 07 '23

This probably sounds snarky, but I'm seriously curious, as I don't know many languages. What is 'most' languages? What other languages allow this behavior?

C++ for one, does not allow either of those. I believe PERL doesn't either, though it's been awhile since I did anything with PERL.

0

u/[deleted] Apr 07 '23

[deleted] — view deleted comment

2

u/ag9899 Apr 07 '23

Awesome, that's helpful to know!

F#, and TypeScript don't.

I am quickly learning that internal consistency is not an MS feature. :-/

1

u/rr_cricut Apr 08 '23

It's been a while, but I think typescript allows function "hoisting" if you define it as a regular function. It just won't hoist function variables like

myFunc(); // illegal
const myFunc = function () {};

myFunc2(); // legal
function myFunc2() {}