c# static public method

8.7k views Asked by At

Within a class called Security, there is a method:

    public static bool HasAccess(string UserId, string ModuleID)

How do I call this method and so it can return a bool result?

I tried the followoing but was not successful:

    Security security = new Security();
    bool result = security.HasAccess("JKolk","Accounting");
4

There are 4 answers

0
Chris Shain On BEST ANSWER

You just use the class name. No need to create an instance.

Security.HasAccess( ... )
0
Tim M. On
bool result = Security.HasAccess("JKolk","Accounting");

To call a static method, you don't need to instantiate the object on which it is being called.

http://msdn.microsoft.com/en-us/library/79b3xss3.aspx

Note that you can mix and match static and non-static members, such as:

public class Foo
{
    public static bool Bar() { return true; }
    public bool Baz() { return true; }

    public static int X = 0;
    public int Y = 1;
}

Foo f = new Foo();
f.Y = 10; // changes the instance
f.Baz(); // must instantiate to call instance method

Foo.X = 10; // Important: other consumers of Foo within the same AppDomain will see this value
Foo.Bar(); // call static methods without instantiating the type
0
Praveen On

As it's a static method, you should do something like below.

 Security.HasAccess(("JKolk","Accounting"); 
0
Jeremy Holovacs On

if it's a static method, then the way to call it would be like so:

bool result = Security.HasAccess("JKolk","Accounting");

you would not use an instance of the Security class, you would use the definition of the Security class.