Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access a static method in c#?

Tags:

c#

oop

When we have a static method in a class it access only static members right and the static method can access only with class name. So I am not able to access the static method in my example:

class myclass
{
    int i  ; static int j ;
    static void get()
    {
        j = 101;
        Console.WriteLine(j.ToString ());
    }
    public void test()
    {
        i = 11; j = 12;
        Console.WriteLine(i.ToString());
        Console.WriteLine(j.ToString());
    }
}
class Program
{
    static void Main(string[] args)
    {
        myclass clsmyclas = new myclass();
        clsmyclas.test();

        Console.ReadLine();
    }
}

}

like image 551
Surya sasidhar Avatar asked Mar 26 '10 06:03

Surya sasidhar


People also ask

Are there static methods in C?

A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.

How do you call a static method from another file?

Access to static functions is restricted to the file except where they are declared. When we want to restrict access to functions from outer world, we have to make them static. If you want access functions from other file, then go for global function i.e non static functions.


3 Answers

You should change it to

public static void get() 

and access it with

myclass.get();

Not an instance of the class.

like image 71
Adriaan Stander Avatar answered Oct 19 '22 02:10

Adriaan Stander


Your issue is a simple one. The default accessor for a static void method is private. Simply add either public or internal in front of the get method and you're good to go.

Also, it would be best not to call the method get to avoid confusion with properties.

like image 39
Enigmativity Avatar answered Oct 19 '22 02:10

Enigmativity


You need to make myclass.get a public method.

like image 24
codenheim Avatar answered Oct 19 '22 03:10

codenheim