0
hey guys I am in method and i didn't interstade why we write static when our method has no return but when we our method have a
int Sqr(int x) { int result = x*x; return result; } static void SayHi() { Console.WriteLine("Hello"); }
2 ответов
+ 3
The static keyword is used to invoke the sayHi (); method in your main method without having to generate an instance (object) of your class Program.
namespace SoloLearn
{
    class Program
    {
        static void sayHi() // with static keyword
        {
            Console.WriteLine("Hello");
        }
        static void Main(string[] args) // main method
        {
            sayHi(); // method call
        }
    }
}
If that word is not used, as you can see, your method sayHi(); is in the Program class, so you should create an instance (object) of that class to be able to use it.
namespace SoloLearn
{
    class Program
    {
        void sayHi() // without static keyword
        {
            Console.WriteLine("Hello");
        }
        static void Main(string[] args)
        {
            Program anObject = new Program(); // New object of Program class
            anObject.sayHi(); // call method from your object
        }
    }
}
You will understand it better when you get to class lessons.
+ 4
Use of the `static` keyword has no relation to return statements.
https://www.sololearn.com/learn/CSharp/2666/






