class or struct?

  • Thread starter Thread starter Sunny
  • Start date Start date
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
 
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.
 
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
 
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
 
Back
Top