Readonly Global Variables?

  • Thread starter Thread starter blue
  • Start date Start date
B

blue

I know, I know, global variables are bad bad bad.

I have some readonly variables that I assign right away and they will never
change (hence the "readonly" part). I need to access these variables in
multiple classes and I don't want to have multiple declaractions all over
the place and have to remember where to update everything when I decide to
change a value in my code.

Where/how do you do this? Since I'm using ASP.NET, maybe I could put them
in the global.asax? That sounds like a really bad idea though.
 
Blue,

If the values are constants, then you can declare public constants on a
class and then they can be accessed anywhere that the class is available.
If you need to do some computation before setting the read-only variable
(for example, say you want to store the machine name, it can't be a
constant, but it is constant throughout the lifetime of the app). You can
set these variables in a static constructor for your type.

Which class you do it in is up to you. Global is a choice. As long as
it is visible to the other types that want to access it.

Hope this helps.
 
Thanks for the ideas. I decided to make an abstract Globals class and I
made the variables public, readonly and static. I made them readonly rather
than constant because our coding standards say that we should only use
constant for well known constant types (like the days of the week) and
everything that is specific to our project should be readonly.

Now I know the difference between readonly and constant.
 
Telmo Sampaio said:
mmm... you could use a static class for that... and a static constructor.

What exactly do you mean by "a static class"? There's no such thing in
C#, as far as I know.
 
Back
Top