Reputation: 1186
I have several static fields and need to know what is the best container for them: class
or struct
?
public class/struct MySharedFields
{
public static readonly string Field1 = AppConfig.GetValue("Field1");
public static readonly string Field2 = AppConfig.GetValue("Field2");
public static readonly string Field3 = AppConfig.GetValue("Field3");
}
Upvotes: 1
Views: 610
Reputation: 2017
When you use a class or struct, first time CLR loads a Type
class. All objects of a type have a reference to that type avaliable via GetType
method. Objects themself contains only instance fields, all methods and static fields are in Type
. Instance methods takes implicit extra argument this
. When you call instance method, object passes himself to method, which actualy defined in Type
. Difference between struct and classes only in where they keep their fields: heap for classes and stack for struct. So there is no real difference between static method of class and struct. But you can mark class as static to prevent creating instances of that class.
Upvotes: 2
Reputation: 15357
The difference between a class and struct in C# is very small.
I would say, use a class, because then you can easily afterwards add methods to it when needed.
Probably structs might have some performance advantages, but if that is not an issue, a class is probably in most of such cases the best way to go.
You can in your case make the class static, unless you have multiple instances or later you want to have multiple instances.
Upvotes: 0
Reputation: 4470
Usually static class is the way to go, but it really doesn't make a difference. The plus is you can add Methods in the future if required.
public static class MySharedFields
{
public static readonly string Field1 = AppConfig.GetValue("Field1");
public static readonly string Field2 = AppConfig.GetValue("Field2");
public static readonly string Field3 = AppConfig.GetValue("Field3");
}
Upvotes: 2
Reputation: 6683
You should use a static class, as C# doesn't allow static structs:
public static class MySharedFields
{
public static readonly Field1 = AppConfig.GetValue("Field1");
public static readonly Field2 = AppConfig.GetValue("Field2");
public static readonly Field3 = AppConfig.GetValue("Field3");
}
Upvotes: 1