apomene
apomene

Reputation: 14389

public vs public static Methods

Having read the access modifiers in C# progamming tutorial, I come to conclusion that defining a method public is enough for it to be "seen" from another Form of the same namespace.

However, in practise whenever I tried to implement this, I also had to define the method as static in order for it to be referenced from other Forms of the same namespace.

Am I loosing something? I am doing somethning wrong?

Upvotes: 5

Views: 10106

Answers (2)

bas
bas

Reputation: 14982

For a public static method, you don't need a reference to an object. The method is static and can be accessed on class level.

If you can't access a public method, then you need a reference to the object, then you can.

public class AClass
{
    public void DoSomething() {}
    public static void DoSomethingElse() {}
}

You can use them as follows:

AClass.DoSomethingElse(); // no object reference required
AClass.DoSomething(); // will give compiler error, since you have no object reference.
var anObject = new AClass();
anObject.DoSomething(); // will work fine.
anObject.DoSomethingElse(); // compile error (thx hvd).

Upvotes: 7

Parimal Raj
Parimal Raj

Reputation: 20595

public static method do not need object instance, they can be used without creating any instance of the class

ClassName.MyStaticPublicMethodName()

where as public (non-static) method require an Instance of the Class, public (non-static) method in general helps you to work with the data member (field) of the object.

To use a non-static public method you need to create instance of the class

ClassName obj = new ClassName();
obj.MyPublicMethod();

Upvotes: 1

Related Questions