C
C#2d ago
Faker

✅ Method declaration, outside Main Vs inside main

Hello guys, consider the following code:
C#
using System;

namespace Learning
{
class Program
{
static void Main(string[] args)
{
DisplayRandomNumbers();

void DisplayRandomNumbers()
{
Random random = new Random();
for (int i = 0; i < 5; i++)
{
Console.WriteLine(random.Next(1,10));
}
}
}


}
}
C#
using System;

namespace Learning
{
class Program
{
static void Main(string[] args)
{
DisplayRandomNumbers();

void DisplayRandomNumbers()
{
Random random = new Random();
for (int i = 0; i < 5; i++)
{
Console.WriteLine(random.Next(1,10));
}
}
}


}
}
At first, I wrote the DisplayRandomNumbers() method outside the Main method but I got an error telling me that I can't call the DisplayRandomNumbers from a static context. Can someone explain why I got this error and why if I put the method inside the main method itself, it works fine. What's happening behind the scenes here?
14 Replies
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
Faker
FakerOP2d ago
Ah, we assume that every method created inside main is also static in nature? even though we didn't use the static keyword ?
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
Faker
FakerOP2d ago
yep, I know from Java, that static means we don't need an instance of a class (an object) to call a method
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
Faker
FakerOP2d ago
ah yeah my bad
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
Faker
FakerOP2d ago
yep sorry
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
Faker
FakerOP2d ago
if we use top level statement, here we must explicitly use the keyword static? I tried it using top level statements, work fine without using the static keyword, but as a good practice, we should include it?
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
Faker
FakerOP2d ago
yeah I see any function declared inside another function, like DisplayRandomNumbers() inside name, "inherits" from the main context, like static access ?
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
Faker
FakerOP2d ago
yep I see, thanks !

Did you find this page helpful?