C
C#16mo ago
mambo no. 5

❔ top level statements

i am using .net 7.0 with top level statements. Why does this work:
Multiply(2, 4);

partial class Program
{
static void Multiply(int num01, int num02)
{
int result = num01 * num02;
Console.WriteLine("The result is: " + result);
}
}
Multiply(2, 4);

partial class Program
{
static void Multiply(int num01, int num02)
{
int result = num01 * num02;
Console.WriteLine("The result is: " + result);
}
}
but not this:
partial class Program
{
static void Multiply(int num01, int num02)
{
int result = num01 * num02;
Console.WriteLine("The result is: " + result);
}
}

Multiply(2, 4);
partial class Program
{
static void Multiply(int num01, int num02)
{
int result = num01 * num02;
Console.WriteLine("The result is: " + result);
}
}

Multiply(2, 4);
Why does the latter throw an error "Can't resolve symbol 'Multiply'"?
12 Replies
Thinker
Thinker16mo ago
Type declarations have to come after all top-level statements
mambo no. 5
mambo no. 5OP16mo ago
so anything that is declared outside of the partial class that i have defined is considerd a top level statement? i thought top level statements were the boilerplate code (namespace, class def, main entry method)
Thinker
Thinker16mo ago
Well, all statements above any type declarations
mambo no. 5
mambo no. 5OP16mo ago
basically i have to call method before define method, correct? oh hol on
mambo no. 5
mambo no. 5OP16mo ago
yup, ur right, applies to all statements
Thinker
Thinker16mo ago
C# doesn't have a concept of declaration order If you define a method Multiply then it exists everywhere, not just after the declaration
mambo no. 5
mambo no. 5OP16mo ago
do you have a link to the docs for that? i can't find anything relating to it online
Pobiega
Pobiega16mo ago
Thats just how C# works. Why would you need documentation for it? Its been that way since .NET Framework 1, C# 1 top level statements isnt magic, it just puts all your code inside a static void Main method This isn't python or javascript, its not interpreted line by line
mambo no. 5
mambo no. 5OP16mo ago
gotcha
cap5lut
cap5lut16mo ago
SharpLab
C#/VB/F# compiler playground.
mambo no. 5
mambo no. 5OP16mo ago
wow that's pretty cool! thanks for sharing :)
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server