views:

18

answers:

3

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?

+1  A: 

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

Steven
+1  A: 

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.

Oded
Thank you, before I accept could you please tell me if when using a method in myClass if I need to create an instance of it, or can I just reference it? Do I need to do protected myobj = new myClass; myobj.myMethod() or can I just to myclass.myMethod()?
Tom Gullen
@Tom Gullen - It depends on how you declare you method. Most methods will require you to instantiate the class before you can use it. If you create them as static, they are then "class methods" that don't need an instance but are tied to the type - think very carfully before doing this, as there are startup costs to doing so.
Oded
+2  A: 

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.).

Timwi
Super, exactly what I was after! Is this considered bad practise? Or is it OK to use?
Tom Gullen
There’s nothing wrong with using this per se. Of course, there are ways of using it badly — for example, don’t make a method static if it could easily just be a method on the type of the first parameter instead.
Timwi
Timwi, yes sure! Sorry I always get worried who's answer I should accept, I did the other one because my comment indicated I would and he was first in, sorry if I offended anyone
Tom Gullen
[Thanks! :)](http://meta.stackoverflow.com/questions/700/)
Timwi