Baba.S
Baba.S

Reputation: 354

What is the significance of 'static' in a method

Looking at the addValues method below, this is not callable if I don't include the 'static' keyword. Why is this so?

namespace TryingMethods
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(addValues(3, 4));
    }

    public static int addValues(int left, int right)
    {
        return left + right;
    }
}
}

Upvotes: 0

Views: 84

Answers (4)

user6590526
user6590526

Reputation:

When you do not say static , it means that the method is a 'property' of the object, which is an instantiation of this particular class. When you do not say static, it means that the method is not a property of the object, and thus, can be called without referring to the object.

For example, you could have a Person class, and there is a static method "Print hello" and there is a non-static method "Give me name". Printing hello is not relevant to the particular person, so it is static. "Give me name" is relevant to the particular person, so you need to call this method differently.

Person myMan = new Person();
myMan.giveMeName();
printHello();

Upvotes: 1

XTimeX
XTimeX

Reputation: 21

It's because static method can only have acces to static variables and other static methods. Normally, you cannot call addValues(int left, int right) inside main() method which is static. Only way around is to have an instance of a class containing addValues() method.

Upvotes: 1

Andrew
Andrew

Reputation: 388

It's because you have your Main function declared as static, so the methods that you call in it need to be too. If you remove static from both you wouldn't get the error.

Upvotes: 0

jsiot
jsiot

Reputation: 126

You don't need to instanciate the class in order to call static methods.

Program.addValues(1,2)

static methods can't get/set class members

Upvotes: 0

Related Questions