views:

150

answers:

4

I'm trying to port some code into .net which has a load of #define'd values e.g.

#define MY_CONSTANT       (512)
#define MY_VERSION_STRING "v42.2"

When I import a cli library the #define's are lost. Is there a way of defining constants in the scope of a namespace. I was thinking something like this:

namespace MyNamespace
{
    const int MY_CONSTANT = 512;
    const String^ MY_VERSION_STRING = "v42.2";
}

So in future I could refer to that as:

int myVar = MyNamespace::MY_CONSTANT;
String^ myVar = MyNamespace::MY_VERSION_STRING;

[Edit] Some of the constants are strings so an enum won't solve the general case.

[Edit2] I'm using C++/CLI here and right now interoperability with other .net languages is not a priority. That said, if there's a more .net-like way of solving this (i.e. standard practice) I'd rather go with that.

A: 

If there are multiple related values, it's usually better to do this with enums. Otherwise, hang them off a class, like:

public static class ConstantStuff
{
   public const int MyConstant = 512;
   public const int SomethingElse = 42;
}

C# doesn't allow "naked" constants.

nitzmahone
C++/CLI does allow constants at namespace scope - but as C# doesn't it becomes an interop problem
Phil Nash
A: 

I believe that if you put them at namespace scope they may not be accessible to C# apps, if that's important to you - best to wrap them in a ref class.

Phil Nash
A: 

You cannot declare constants inside namespaces. You need to define a container to put your consts into, like a class, struct or enum.

public static class MyConstants
{
    public const float ConstantValue1 = 0;
}

and refer to them like this:

float value = MyConstants.ConstantValue1 ;
Trap
you can in C++/CLI, to which this question relates
Phil Nash
+3  A: 

You can define a static class holding public fields that work as constants, eg.

namespace MyNamespace
{
    public class Constants
    { 
        public static int MyConstant1 { get { return 512; } }
        public static int MyConstant2 { get { return 1024; } }
    }
}

Then you can use Constants.MyConstant1 in place of MY_CONSTANT.

Note, though, that having a 'general' constants class is a 'bad practice': the kosher way is to keep related constants in the class related to what they define, eg. if you have a FileParser class that uses a MaxBufferSize constant, you would define a static FileParser.MaxBufferSize constant.

axel_c
That seems like a reasonable compromise. We have a bunch of related functionality which shares some common elements so as a quick and dirty solution, this seems like a workable way of progrssing.
Jon Cage