How to get global values

D

Dom

In C++ and VB, it is pretty easy to get a global constant, one that
can be used by all modules. I still have a need for this in CSharp,
but there is not easy way to get these. I can't, for example, just
"include" a file of constants.

Is it a good idea to create a class like the following:

class Parameters
{
public string FN_RegisteredServers;
public string FN_Sources;

public Parameters()
{
FN_RegisteredServers = Application.StartupPath + "\
\RegisteredServers.xml";
FN_Sources = Application.StartupPath + "\\Sources.xml";
}
}

Then, when a class needs a parameter, it does the following;

Parameters p = new Parameters ();
string FN_RegisteredServers = p.FN_RegisteredServers;

It just seems wrong that I need a new instance everytime I use it.

Dom
 
J

Jon Skeet [C# MVP]

Dom said:
In C++ and VB, it is pretty easy to get a global constant, one that
can be used by all modules. I still have a need for this in CSharp,
but there is not easy way to get these. I can't, for example, just
"include" a file of constants.

It just seems wrong that I need a new instance everytime I use it.

Indeed - they should be static instead, so you don't need to create a
new instance. They should also be readonly though. Use a static
constructor to set them up. Alternatively, follow the singleton
pattern:

http://pobox.com/~skeet/csharp/singleton.html
 
G

Garfilone

In C++ and VB, it is pretty easy to get a global constant, one that
can be used by all modules. I still have a need for this in CSharp,
but there is not easy way to get these. I can't, for example, just
"include" a file of constants.

Is it a good idea to create a class like the following:

class Parameters
{
public string FN_RegisteredServers;
public string FN_Sources;

public Parameters()
{
FN_RegisteredServers = Application.StartupPath + "\
\RegisteredServers.xml";
FN_Sources = Application.StartupPath + "\\Sources.xml";
}
}

Then, when a class needs a parameter, it does the following;

Parameters p = new Parameters ();
string FN_RegisteredServers = p.FN_RegisteredServers;

It just seems wrong that I need a new instance everytime I use it.

Dom

just create a static class to store these static global values, a
utility class
 
J

Jon Skeet [C# MVP]

Dom said:
Thanks for this. Is there any practical reason why I would choose a
static class instead of a singleton?

If you never need anything other than constants, and don't need to use
the singleton instance for any other purpose, a static class can be
simpler. On the other hand, it can be less extensible later on - using
a singleton, you can often keep the fact that it *is* a singleton away
from quite a lot of other classes, which can make unit testing easier
etc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top