+ 1

Methods and classes... where should be declared?

Hello... just a quick question... generally speaking where should methods and classes be declared? I did some experiments (I started with JavaScript where there is no Main() method). In some cases when I declare a method several errors appear... should I declare them before the main? Maybe I spot my mistake... I was not adding "static" before the method... but still... should classes and methods be declared outside the main (maybe with the 'static' keyworld) or is it me that understood wrong?

2nd Mar 2017, 11:29 PM
Daniele
Daniele - avatar
6 ответов
+ 14
Methods cannot contain methods. Classes can contain methods. The main method is where the code starts. The main method is static and therefore can only call static methods. You can learn more about the static keyword from the SoloLearn C# course 🍰
3rd Mar 2017, 12:25 AM
Jafca
Jafca - avatar
+ 14
In C#, the methods don't have to be declared before the main method. They can be declared after it too (but not inside it). And yes, to the second part. If you're starting off and only using the class that the main method is in, then use static on all methods. When you start using multiple classes, you'll realise what static really means
3rd Mar 2017, 9:01 AM
Jafca
Jafca - avatar
+ 13
"The Main method is static, as it is the starting point of any program. Therefore any method called directly from Main had to be static." Source: SoloLearn C# course > More On Classes > Static Members > Page 3
3rd Mar 2017, 12:28 AM
Jafca
Jafca - avatar
+ 3
Main is a method, so it cannot have other methods declared in it. However, it can call other methods outside of Main, either a static method or a method within a class. Classes can exist within other classes, but they cannot exist within methods (including Main).
3rd Mar 2017, 12:30 AM
Anthony Vanover
Anthony Vanover - avatar
0
I also tried to declare variables... I noticed that if I do it outside the Main() they need the static keyword but inside just the type... am I do it right? It seems so weird to add so much just to declare a single variable. The problem is that the course usually 'cuts' the first part of the code to save time...
4th Mar 2017, 10:45 AM
Daniele
Daniele - avatar
- 1
So all the classes and methods should be declared outside (before) the main method. In this way all the methods but the once created inside of a class should have the static keyword? All of this is kinda new for me... Javascript is a great language to start, as it is easy to compile, but when you jump into more 'complex' languages the drawback is being stuck in small problems...
3rd Mar 2017, 8:56 AM
Daniele
Daniele - avatar