C/VB to C# - newbie question about shared constants

1

13 Fallen

Hello,

This is a newbie question.

There are two ways I have handled shared constants in C and in VB:
* a header (H) file in C that is shared by one or many projects
* a module (BAS) file in VB that is shared by one or many projects

These constants are usually special strings and special numbers that need to
be shared across a family of applicaitons.

I understand that I cannot put constants inside an empty C# (CS) source
file, although they can be placed inside a class or struct definition inside
a namespace.

Is it always better programming practice to have constants always associated
with a class or struct?

Can I use a namespace and abstract class to hold global constants?

Thanks,

-G
 
N

Nicholas Paldino [.NET/C# MVP]

G,

Even better would be a sealed class, to prevent anyone from extending
the class. You could then have constants and static read-only fields if you
wished, and no one could derive from your class.

The next version of C# will introduce static classes, which would make
this task much easier. Static classes allow you to define a class as
static, and you get a compile-time error whenever you try to add instance
fields to it. Additionally, it takes care of preventing instances from
being instantiated.

Hope this helps.
 
M

Morten Wennevik

Hi 13Fallen,

Create a public sealed class with a private constructor and put public
const values inside
This is how the Math class works, with Math.PI as a public const value,
and with every method static.


Happy coding!
Morten Wennevik [C# MVP]
 

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