Jan Turoň
Jan Turoň

Reputation: 32912

Is there a way how to use constants without scope resolution?

I really miss C #define in C#; in C# #define reference says:

The #define directive cannot be used to declare constant values as is typically done in C and C++. Constants in C# are best defined as static members of a class or struct. If you have several such constants, consider creating a separate "Constants" class to hold them.

So I'd like to have something like this:

class Constants {
  public static const int UP=0, DOWN=1, LEFT=2, RIGHT=3;
  ...
}

class Foo {
  public Foo(int dir) {
    // import Constants scope here (and some other classes) somehow
    if(dir==UP) ...
    // ...because this is far worse readable
    if(dir==Constants.UP)
  }
}

Is it possible? If yes, how?

Upvotes: 1

Views: 111

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

I suggest you not to use such generic word as Constants for class which holds all your constants. Because it does not give any context to constants you have. And I don't suggest to keep all constants in one class. Create small contexts for each set of related constants. And give appropriate name for each small context.

There is nice way to group related named constants in one context - enumerations. So, create enumeration for your direction constants and give descriptive name to that enumeration:

public enum MoveDirection
{
    Up,
    Down,
    Left,
    Right
}

Now Up is not Pixar Movie - its move direction:

switch(direction)
{
     case MoveDirection.Up:
         // ...
}

Upvotes: 2

Roy Dictus
Roy Dictus

Reputation: 33139

Put this on top of your code:

using UP = Constants.UP;

then you'll be able to use

if (dir == UP) ...

Upvotes: 0

ohlmar
ohlmar

Reputation: 956

You would want to use Enumeration (http://msdn.microsoft.com/en-us/library/sbbt4032.aspx).

public enum Something 
{
   UP=1, 
   DOWN=2,
   ....
}

Then you can us it like.

if(dir==Something.UP)

Upvotes: 0

Related Questions