5

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?

Jim Aho
  • 9,932
  • 15
  • 56
  • 87
apomene
  • 14,282
  • 9
  • 46
  • 72
  • Did you create an instance of the class that the method resides in? Was the class marked as static too? Post some code – DGibbs Mar 17 '13 at 18:28
  • Possible duplicate of [When should I use public/private/static methods?](http://stackoverflow.com/questions/793494/when-should-i-use-public-private-static-methods) – Ashraf Sada Jul 31 '16 at 14:37

2 Answers2

7

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).
bas
  • 13,550
  • 20
  • 69
  • 146
  • "anObject.DoSomethingElse(); // will also work fine" -- Are you sure? Mono's compiler gives a hard error "error CS0176: Static member cannot be accessed with an instance reference, qualify it with a type name instead", and I seem to recall seeing an error for that with Microsoft's compiler as well. –  Mar 17 '13 at 18:37
  • In fact, that error code CS0176 [is Microsoft's code for that exact error](http://msdn.microsoft.com/en-us/library/zhcxt2bd%28v=vs.90%29.aspx). –  Mar 17 '13 at 18:39
1

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();
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110