473,903 Members | 3,244 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2897
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******@hotma il.com> wrote in message
news:5%Aue.7267 1$HI.43005@edtn ps84...
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.NameOf App;

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.CurrentT hread 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 MaxMessageLengt h = 255;

You can then...

if (strMsg.Length > Logger.MaxMessa geLength) ...

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.MyStri ng = "NewValue";

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

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

Bruce Wood <br*******@cana da.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.co m>
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.Con stant1".

Does the compiler will place the constant value inline everywhere the
"myClassObj.Con stant1" 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.publi c.dotnet.csharp .general]

Marty <xm******@hotma il.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.Con stant1".

Does the compiler will place the constant value inline everywhere the
"myClassObj.Con stant1" 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.co m>
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
2715
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 called $glb. So, every function so far looks like this: function something() { global $glb; }
10
17901
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 overwrite another copies global variable? I know that you could overwrite a value in a global variable from a function, but you could also do that if you pass the variable in and then out again... so how is that any different?
20
4515
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 structurally sound to use Application_OnStart. Am I attempting the impossible, and if so, why?
1
3854
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 are quite a few things that I learned that I did not know before. For example, while I knew that the new and delete operators can be overloaded for classes, I did not know that that the global new and delete operators can also be overloaded. ...
25
66089
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 layers/objects/etc... or does it expect me to create a singleton global class structure? surely it's not that terrible.
4
2033
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 . How do I perform this in C#? p.e. string NE_01_001 = "Granulator";
4
51187
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 a wise idea to create a clsCommonApp and let all other classes to be derived from that class? and define all constants in that base class? Any other suggestions are more than welcome. (BTW this is not for one constant, I have multiple...
8
5683
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 without having to jump through a bunch of hoops. First, let me layout how it worked in 1.1. In the Global.asax, within the Global class construct, I would simply add something like: public const string FOO = "foo";
6
1643
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 including config.php and declaring the variables that will be used as global. This seems very inefficient. 2.Moreover these variables are constants, is there a way to make the variables unmodifiable in config.php so that scripts that use them ,
0
9999
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11282
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10873
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10983
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10500
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9684
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8048
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5894
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
4308
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.