How to Access a static method in c#?

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();
    }
}

}

Answers


You should change it to

public static void get() 

and access it with

myclass.get();

Not an instance of the class.


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.


You need to make myclass.get a public method.


The default accessibility of a member is the most private that is possible for it. That means that your method is private as you haven't specified any accessibility level.

You have to specify it as public (or internal if you only need access within the same project) to reach it:

public static void get()

or:

internal static void get()

You can have any access modifier you want on your static methods.

Access of course only limits the way it is used outside the class itself.

However, static methods cannot use the this keyword as references to the parent class.

Depending on the access level of the method you can call a method statically as:

ClassName.Property
ClassName.Method
ClassName.Field

Need Your Help

UIManagedDocument nested Contexts

iphone core-data nsmanagedobjectcontext uimanageddocument

I've been reading apple documents and still there is a question, that a i can't find an answer for. I've got an UIManagedDocument object, which has two nested contexts - the child one on a main thr...

Hide button on first of two UIViews, but have it visible on second

objective-c iphone uiviewcontroller uinavigationbar uibarbuttonitem

So I have a UIViewController (main application controller is a TabBarController). On this there is a UINavigationBar, and a UIBarButtonItem. I'm PRETTY sure I hooked up everything correctly in the