Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store consts in a struct or a static class

Tags:

c#

constants

If I have a set of string constants that I want to store similar to an enum, is it best to use a struct or a static class? For example:

public struct Roman
{
    public const string One = "I";
    public const string Five = "V";
    public const string Ten = "X";
}

public static class Roman
{
    public const string One = "I";
    public const string Five = "V";
    public const string Ten = "X";
}
like image 797
Hand-E-Food Avatar asked Aug 21 '14 03:08

Hand-E-Food


People also ask

What is the difference between static and non static classes?

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type.

Should I use a struct or a static struct?

Structs are normally avoided unless they meet certain criteria as detailed in this answer. Since your co-worker is not using it to store a value, he should be using a class, not a struct. Show activity on this post. I think static is better and here's my reasoning.

How many times can a static constructor be called in C?

A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides. To create a non-static class that allows only one instance of itself to be created, see Implementing Singleton in C#.

How many static members can be created in a class?

Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.


1 Answers

A static class is more traditional in the C# environment. The primary disadvantage of using a struct is that you could accidentally create an instance of it. A static class will prevent this. (Under the hood a static class is abstract sealed, so you cannot create an instance of it, nor can you derive from it. You cannot make a struct abstract, nor can you make the no-argument constructor private, so there is no way to create an "unconstructable" struct.)

Neither approach will have any impact on performance or behavior of the constant values.

like image 193
cdhowie Avatar answered Oct 31 '22 16:10

cdhowie