Reno
Reno

Reputation: 1319

What is better way to implement static global collections?

I am thinking what is the best way to load data to collections if it is global per application;

public static class ErrorValues
{
        public static readonly Dictionary<int, string> errorInfo = new Dictionary<int, string>
        {
            {0, "Error 404"},
            {1, "Error 500"},
            {2, "Error 301"}
        };
}

or like this

public static class ErrorValues
{
    public static Dictionary<int, string> errorInfo;

    static ErrorValues()
    {
      if (errorInfo == null)
      {
        errorInfo = LoadDataToDictionary();
      }
   }
}

better solutions? Why?

Upvotes: 0

Views: 945

Answers (3)

sloth
sloth

Reputation: 101122

If your data is static, I recommend creating a meaningful type

Example:

public class ErrorValue
{
    private static Dictionary<Int32, ErrorValue> _errors;

    public static readonly ErrorValue Error404 = new ErrorValue(404, "Error 404");
    public static readonly ErrorValue Error500 = new ErrorValue(500, "Error 500");
    public static readonly ErrorValue Error301 = new ErrorValue(301, "Error 301");

    public String ErrorName { get; private set; }
    public Int32 ErrorCode { get; private set; }

    private ErrorValue(Int32 errorCode, String errorName)
    {
        if (_errors == null)
            _errors = new Dictionary<int, ErrorValue>();

        ErrorName = errorName;
        ErrorCode = errorCode;

        _errors.Add(errorCode, this);
    }

    public static IEnumerable<ErrorValue> Errors { get { return _errors.Values; } }

    public static ErrorValue GetErrorByCode(Int32 errorCode)
    {
        return _errors[errorCode];
    }
}

This will lead to a less error-prone code due to type safety, since you can write methods with paramters of type ErrorValue:

void HandleError(ErrorValue ev)
{ 
    // bla bla
}

Another benefit is that with this approach, you can easily extend the type; e.g. add other properties like Description, without huge changes to your code.

If you need similar static global collections, you can extract a common generic base class to provide methods like GetById or GetByName or similar.

Upvotes: 3

Shoaib Shaikh
Shoaib Shaikh

Reputation: 4585

I think the first one is simple if items are static/hard coded and not to be loaded from DB or some other data source.

Second one is using singleton pattern that is used heavily in applications where object is to be created only once and reuse that object reference throughout the life cycle of application. and offers to initialize collection from any other data sources.

Conclusion: both are good but depends on what you need. personally i like the second way as it follows a design pattern.

Upvotes: 1

Ventsyslav Raikov
Ventsyslav Raikov

Reputation: 7202

There should be no difference in the generated IL except the beforefieldinit flag.

Upvotes: 1

Related Questions