views:

436

answers:

4

Is there any way to define a constant for an entire namespace, rather than just within a class? For example:

namespace MyNamespace
{    
    public const string MY_CONST = "Test";

    static class Program
    {
    }
}

Gives a compile error as follows:

Expected class, delegate, enum, interface, or struct

+1  A: 

This is not possible

From MSDN:

The const keyword is used to modify a declaration of a field or local variable.

Since you can only have a filed or local variable within a class, this means you cannot have a global const.

Oded
A: 

No, there is not. Put it in a static class or enum.

svinto
+15  A: 

I believe it's not possible. But you can create a Class with with only constants.

public static class GlobalVar
{
    public const string MY_CONST = "Test";
}

and then use it like

class Program
{
    static void Main()
    {
        Console.WriteLine(GlobalVar.MY_CONST);
    }
}
PoweRoy
+1 as this is the Microsoft recommended method http://msdn.microsoft.com/en-us/library/bb397677.aspx
Bryan
A: 

I'm not sure, but I think that defeats the purpose of OOP. OOP is basically objects 'talking' to each other. And you want to declare the variable in the 'Matrix' full of objects. Namespaces are used to segregate the code.

Maybe use static class instead?

Mike