Tim Bostwick
Tim Bostwick

Reputation: 332

Accessing public methods in same class requires an Instance?

I'm a newbie to C# so forgive this question but I'm confused: Why do I need an instance of class Program to access method Sandbox which is public and in the same class?

namespace GoogleTest
{
    class Program
    {
        static void Main(string[] args)
        {    
            Program p = new Program();
            p.Sandbox();            
        }

        public void Sandbox()
        {
            ...
        }
    }
}

Upvotes: 1

Views: 933

Answers (3)

T McKeown
T McKeown

Reputation: 12857

Static methods exist at the Class level, you can consider them Global functions. Any non static methods are instance level and just as the name implies you can only execute instance methods on an instance. So by instantiating the class you have created an instance and now can call any public method. In your example you could also call any private methods or constructors because you are creating the instance from with the class you are creating.

Upvotes: 1

Eugen Rieck
Eugen Rieck

Reputation: 65332

public void Sandbox()
{
   ...
}

is the important part: This method is not marked static, so it is not callable on the class, but on instances of the class. If you want to be able to call it directly, you need

public static void Sandbox()
{
   ...
}

and can't use this.

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564851

Because you're trying to access it from within a static method, but Sandbox is an instance method.

If you make Sandbox static, this won't be required:

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

public static void Sandbox()
{
        ...
}

Note that it also doesn't have to be public - public allows it to be used by other classes and within other assemblies, but within Program, that's not required.

Upvotes: 1

Related Questions