1

As soon as I started programming C# (ASP.NET) I was surprised at how restrictive constants were. So far, I haven't used them much and I feel I missed the concept. How would you guys make use of constants in a typical ASP.NET application?

How would declare a constant struct such as System.Drawing.Color?

Would you guys use readonly when const cannot be used?

I would like to find out how people are using const and readonly and to discuss alternatives if any.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
maxbeaudoin
  • 6,546
  • 5
  • 38
  • 53

3 Answers3

1

Constants are for defining things in your program that should not change, but need to be referenced multiple times.

const int SLEEP_TIME = 500; //500 MS = .5 Seconds
//Do Something
Thread.Sleep(SLEEP_TIME);
//Do Something else
Thread.Sleep(SLEEP_TIME);
//Do yet another something.

Now if you want to change SLEEP_TIME you can do it in one place.

As for a constant struct I'd usually use an enum

enum State
{
   Stopped = 0,
   Running = 1,
   Paused = 2
}

Readonly is useful for references that need to be assigned once

private static readonly Logger = new TextLogger();

And if you need to change something (ie: initialize something to null, then change it), it by definition can't be const.

C. Ross
  • 31,137
  • 42
  • 147
  • 238
1

Just from my experience, I've found that a lot of things that I think are constant, really aren't. I end up using a lot of external settings files to hold the information in (who wants to recompile a site if a color changes?)

That said, I've found constants REALLY good for working with array indexes. It helps clarify their intent. For example...

//not readable - variable names don't help either
string a = (string)source[0];
int b = (int)source[1];
bool c = (bool)source[2];

Or the same thing with constants...

const int 0 = NAME_COLUMN;
const int 1 = AGE_COLUMN;
const int 2 = IS_ADMIN_COLUMN;

//even with bad variable names, we know what they are
string a = (string)source[NAME_COLUMN];
int b = (int)source[AGE_COLUMN];
bool c = (bool)source[IS_ADMIN_COLUMN];
hugoware
  • 35,731
  • 24
  • 60
  • 70
1

Check this out, some of the answers may help you out...

When, if ever, should we use const?

Community
  • 1
  • 1