473,396 Members | 2,036 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Global constants and object

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
Nov 17 '05 #1
8 2847
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.

Nov 17 '05 #2
"Marty" <xm******@hotmail.com> wrote in message
news:5%Aue.72671$HI.43005@edtnps84...
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
Nov 17 '05 #3
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;

Nov 17 '05 #4
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

"Marty" wrote:
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

Nov 17 '05 #5
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.

Nov 17 '05 #6
[Removed invalid group microsoft.public.dotnet.csharp.general]

Bruce Wood <br*******@canada.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #7
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

Marty wrote:
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

Nov 17 '05 #8
[Removed invalid group microsoft.public.dotnet.csharp.general]

Marty <xm******@hotmail.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: mrbog | last post by:
I have an array/hash that stores path information for my app. As in, what directory this is in, what directory that's in, what the name of the site is, what the products are called, etc. It's...
10
by: Matt | last post by:
Greetings, What are people's thoughts on global variables in C++? Why are we taught not to use them in programming? Is it true that if you are running two copies of the C program one copy can...
20
by: 2obvious | last post by:
I've been trying to create read-only global variables by creating constants (Const) in my global.asa, but I can't seem to reference them. Sticking them in an include works fine, but it seems more...
1
by: Nimmi Srivastav | last post by:
There's a rather nondescript book called "Using Borland C++" by Lee and Mark Atkinson (Que Corporation) which presents an excellent discussion of overloaded new and delete operators. In fact there...
25
by: Daniel Bass | last post by:
how do i declare a global variable in c#.net? it's like it want's everything in classes... there are times when globals are good, like having constants in a program which apply to several...
4
by: G.Esmeijer | last post by:
Hi, I would like to use a couple of hundred constant string variable throught my program. I want to use them from every corner of the software. In Vb I jst declared the global and it worked ....
4
by: Amadelle | last post by:
Hi all and thanks again in advance, What is the best way of defining global constants in a C# application? (A windows application with no windows forms - basically a set of classes). Would it be...
8
by: Thomas Coleman | last post by:
Ok, I've obviously discovered that Global.aspx has been completely changed in ..NET 2.0. However, I haven't figured out how to declare a constant that's available to any page in my application...
6
by: lazy | last post by:
hi, I have some constants defined in a php script say config.php. I want to use the variables there defined in other scripts. couple of questions regd that: 1. Is there an alternative to...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.