© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•13mo ago•
34 replies
Faker

✅ Method declaration, outside Main Vs inside main

Hello guys, consider the following code:

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));
                }
            }
        }

        
    }
}
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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

how to write method outside the main method in the program class?
C#CC# / help
2y ago
interface vs extension method vs method in class
C#CC# / help
3y ago
How do I close console app outside of the Main method?
C#CC# / help
3y ago