tags:

views:

162

answers:

3

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.

+1  A: 

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
+1 "Readonly is useful for references that need to be assigned once"
Maxime
+1  A: 

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
I like your point on considering recompiling the website when declaring constants. +1. It's a discussion after all...
Maxime
+1  A: 

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

http://stackoverflow.com/questions/555534/when-if-ever-should-we-use-const

DaveParsons
I've read that thread, I just want to discuss uses of constants in a web application context, giving examples of best practises, things that should be constant such as error messages, things that should never be like a System.Drawing.Color maybe? I don't know. I must admit, that your thread is evolving in that direction tho.
Maxime