class or struct?

S

Sunny

Hi,
I want to create a separate container for a bunch of constants used in
different classes, like:

internal class Constants
{
private Constants(){}

public const string CONST1 = "1";
.....
}

So, what's better for this container, to be class or struct? Why?

Sunny
 
D

Dan Bass

I may be wrong but when you reference a static (const in this case) variable
an instance of the class object in which it resides is not created, not sure
if this is the case with struct being a value type...
If it is then doesn't matter. If it isn't, go with the class.
 
S

sadhu

It really doesn't matter, because the compiler substitutes constants
with their actual values when compiled to IL. One thing that might
irritate you is that you can't prevent construction of a struct i.e you
can't define a private default constructor. So if Constants is a
struct, you will be able to write code like new Constants().CONST1. The
compiler will then report an error that you can access CONST1 only
using the type name. So, I'd suggest going with a class, it atleast
avoids the above possibility.

Regards
Senthil
 
S

Sunny

It really doesn't matter, because the compiler substitutes constants
with their actual values when compiled to IL. One thing that might
irritate you is that you can't prevent construction of a struct i.e you
can't define a private default constructor. So if Constants is a
struct, you will be able to write code like new Constants().CONST1. The
compiler will then report an error that you can access CONST1 only
using the type name. So, I'd suggest going with a class, it atleast
avoids the above possibility.

Regards
Senthil

Thanks Dan and Senthil.

I was wondering if the compiler is substituting during the compile time.
If this is so, then class is better approach.

Do you have any links where it is explained?

Sunny
 

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