简体   繁体   中英

ASP.net c# publicly accessible functions in namespace

In my namespace I can have public classes which are accessible to all other pages in my namespace. How do I go about having public functions? Do I have to create a class with the functions in it? Or is there an easier way?

In C#, all functions (which are actually called methods in C# terminology) are to be declared in a type (a class or a struct).

However, there is the concept of static classes in C#, which are good for the purpose of replacing “global functions” in older programming languages:

public static class MyUtilityFunctions
{
    public static void PrintHello()
    {
        Console.WriteLine("Hello World!");
    }
}

Now you can, anywhere in your program, write:

MyUtilityFunctions.PrintHello();

A static method is a method that doesn't require an object. A static class is a class that contains only static methods (and static fields, static properties etc.).

Functions (Methods) "live" in types, so you need to put them in classes or structs. By default they would be private so you need to specify the public access modifier for them to be accessible:

namespace myNameSpace
{
  public class myClass
  {
    public void MyMethod()
    {
    }
  }
}

See MSDN - Methods section of the C# programming guide.

When doing C#, functions can only live in types (classes and structures). You can not declare a function on its own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM