maxbeaudoin
maxbeaudoin

Reputation: 6976

What are some examples or uses of constants in ASP.NET web applications?

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.

Upvotes: 1

Views: 3730

Answers (3)

hugoware
hugoware

Reputation: 36397

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];

Upvotes: 1

C. Ross
C. Ross

Reputation: 31848

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.

Upvotes: 1

user61470
user61470

Reputation:

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

When, if ever, should we use const?

Upvotes: 1

Related Questions