Defining constants in namespaces?

  • Thread starter Thread starter Tim
  • Start date Start date
T

Tim

Is it possible to define constants in the namespace block? I don't see
any const keyword in the IntellSense when I'm in the namespace block.
Why did Microsoft not allow this, and what is the workaround?

Thanks!

[Tim]
 
   Is it possible to define constants in the namespace block?  I don't see
any const keyword in the IntellSense when I'm in the namespace block.
   Why did Microsoft not allow this, and what is the workaround?

Thanks!

[Tim]

Hi Tim,

A namespace allows you to define certain constructs, e.g., classes,
structs, etc. Constants are not allowed. So, if you need "global"
constants, there are a few alternatives.

1. Define an enum, e.g., enum Instruments { Guitar, Piano };
2. Define a public class with public, constant (or readonly) fields,
e.g.,:

public class Globals {
const int GUITAR=100;
const string MUSICIAN="Hendrix";
}

You can then access via Globals.GUITAR and Globals.MUSICIAN

John Puopolo
 
Back
Top