1

I thought that when your method is public you could invoke it from any class in your project...

namespace MethodTest
{
    class Program
    {
        public static void Foo()
        {
        }

        static void Main(string[] args)
        {
            Foo();
        }
    }

    class MyClass
    {
        public static void asd(string[] args)
        {
            Foo();
        }
    }
}

However when I try to invoke it from an other class I get an error

Error CS0103 The name 'Foo' does not exist in the current context MethodTest D:\Visual Studio\MethodTest\MethodTest\Program.cs 23 Active PS: And as I know if miss the access modifier it is private... Am I correct?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
melany
  • 13
  • 3

1 Answers1

3

You cannot use a method from a different class like this.

Try the following code:

class MyClass
{
    public static void asd(string[] args)
    {
        Program.Foo();
    }
}

This way by using Program.Foo(); you specify which exact method (from the different Program class) you want to use so that the CLR knows which method to invoke.

The reason why to call it like this is the static keyword in the declaration of the Foo method. Otherwise it would be called differently:

new Program().Foo();
Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
  • what about the second part of my question, is the default access modifier private?(when I don't specify it in my program, example:`static void Foo() { }`) – melany Feb 07 '17 at 19:32
  • 1
    The reason why to call it like this is the `static` keyword. Otherwise it would be called differently. The answer is incomplete – Thomas Weller Feb 07 '17 at 19:32
  • 1
    @ThomasWeller I agree with you. I will update my answer. – Nikolay Kostov Feb 07 '17 at 20:48