Global constants and object

M

Marty

Hi,

I'm new to C#, I used to code in VB.NET. Where is the best place to
declare all my constants and global objects in my C# project to have
them accessible globally?

I have an event logger class that I want its instance to be accessible
from any other classe in the project.

There is also a bunch of constants that I want to be public for the
whole program.

Many thanks,
Marty
 
B

Bruce Wood

Use the Singleton pattern for your event logger class. See Jon Skeet's
page on Singleton:

http://www.yoda.arachsys.com/csharp/singleton.html

As for constants, they can live in any class, so you should put them in
the class to which they pertain. For example, if you have a constant
for the log file name, you should put it in your logger class:

public class Logger
{
public const string LogFileName = ... ;
}

Creating a class called "Constants" is very bad style. Each constant
logically belongs with some business object or some business concept,
so put it in the class that represents that thing. Free-floating
constants that don't really belong anywhere hint at a design problem in
your class hierarchy, IMHO.
 
M

Michael Rodriguez

Marty said:
Hi,

I'm new to C#, I used to code in VB.NET. Where is the best place to
declare all my constants and global objects in my C# project to have them
accessible globally?

Hi Marty,

Just create a new class with some static properties then reference that
class whenever you need the values.

HTH,

Mike Rodriguez
 
B

brian.fairchild

One thing you can do is have a Business class (or some other name) that
exposes the properties as static fields:

public class Business
{
public static string NameOfApp= "My New App";
}

then you can get to it from anywhere:

lTitle.Text = Business.NameOfApp;
 
G

Guest

Welcome. In regards to your question there really is no concept of a true
global object in C#. Everything is scoped inside a class. To achieve the
illusion of a global you can create a static class that holds the object as a
static member. As an example, to correlate with your question, I have a
static Logger class in most of my projects that exposes static methods to log
information to various listeners. The Logger class acts as a global object
since it is static. If you need to store data with your static class then
you can either create the data as static (generally only advisable for truly
global, state data) or use the singleton pattern to create an instance of
your non-static class and then expose the instance through a static method.
As an example the Debug and Trace classes in .NET are static classes that
expose static methods. Thread.CurrentThread is a pseudo-singleton class that
exposes (through a static property) the current thread's instance data.

In C# pre-2.0 you make a class static by using the following model:

public sealed class Logger
{
private Logger ( ) { }
...

public static void LogThis ( ) { }
public static void LogThat ( ) { }
}

Then in code I can:

Logger.LogThis();
Logger.LogThat();

This doesn't truly make the class static it simply prevents anyone from
using it as an instance class. In 2.0 you can apply the static modifier to
the class declaration to make it a static class. Within your static class
(not in 2.0 though) you can have both static and instance members (like
Thread does). A true static class has only static methods and properties
(like Debug).

For a singleton-pattern you would do the following:

public sealed class Logger
{
private Logger ( ) { }

public Logger Current
{
get { return m_Instance; }
}

public void LogThis ( ) { }
public void LogThat ( ) { }

private static Logger m_Instance = new Logger();
}

and then...

Logger.Current.LogThis();
Logger.Current.LogThat();

The above implementation is defacto and handles most of the multithreading
issues involved with singletons and delays the creation of the instance until
it is actually needed.

For constants you can simply expose them as constants off of any class that
is most appropriate. For example in the logger class you might want to
expose a maximum message length so in the Logger class you would add

public const int MaxMessageLength = 255;

You can then...

if (strMsg.Length > Logger.MaxMessageLength) ...

If your constants are unrelated to anything then you can create a separate
static class that holds nothing but the constants. I do this for file
parsers. I store all the constants that I use within a file parser in a
separate file. This keeps the main parser class clean but still gives me the
constants.

Others may have other ideas as well.
Michael Taylor, MCP, MCAD - 6/23/05
 
B

Bruce Wood

Do not use

public static string MyString = "Value";

this is probably not what you want. You should instead use

public const string MyString = "Value";

for a couple of reasons.

1. "const" objects are assumed to be static, so you lose nothing by
doing this.
2. If you declare a string "public static" then it is a _variable_ and
can be changed by any method in any other class. Some other class can
say:

TheClass.MyString = "NewValue";

and the "constant" will change. Ouch! "const" prevents this.
 
J

Jon Skeet [C# MVP]

[Removed invalid group microsoft.public.dotnet.csharp.general]

Bruce Wood said:
public static string MyString = "Value";

this is probably not what you want. You should instead use

public const string MyString = "Value";

for a couple of reasons.

1. "const" objects are assumed to be static, so you lose nothing by
doing this.
2. If you declare a string "public static" then it is a _variable_ and
can be changed by any method in any other class. Some other class can
say:

One alternative is to use

public static readonly string MyString = "Value";

That has the advantage that if you use it in a different assembly, the
value doesn't get compiled into that other assembly - if the assembly
containing the constant changes (say you want to change from "Value" to
"Value2") then with const you'd have to recompile and redistribute the
assembly which is using the value as well as the one declaring the
value.
 
M

Marty

Thank you everybody for your help,

The singleton pattern seem very interesting, I'll read on that.

Concerning the global constants, let's say that I place the constants
within a class, then access one of them by "myClassObj.Constant1".

Does the compiler will place the constant value inline everywhere the
"myClassObj.Constant1" is called?

This is because I need full speed at runtime, I don't want it to make
overhead calling the constant like if it was a variable.

Thank you :)
Marty
 
J

Jon Skeet [C# MVP]

[Removed invalid group microsoft.public.dotnet.csharp.general]

Marty said:
Thank you everybody for your help,

The singleton pattern seem very interesting, I'll read on that.

Concerning the global constants, let's say that I place the constants
within a class, then access one of them by "myClassObj.Constant1".

Does the compiler will place the constant value inline everywhere the
"myClassObj.Constant1" is called?

It does if it's declared as const; it doesn't if it's declared as
public static readonly.
This is because I need full speed at runtime, I don't want it to make
overhead calling the constant like if it was a variable.

The JIT should be able to compile the value in if it's a readonly value
type or string (the latter being immutable) although I haven't checked
to make sure that it does.

I would be very wary of worrying about this kind of thing though - the
performance hit for that referencing a static variable in another class
is very, very, very unlikely to be a bottleneck in your code.
 

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