0

Hello I have static class lets say

    internal static class MyStaticClass {
        private static readonly IDictionary<SomeStringType, string> someDicName = 
           new Dictionary<SomeStringType, string> {
           {someEnum.enum, "SomeText"},
        }
    }

But I need to add new value inside this enum based on some global value is there any possibility how can I do it? In normal class I can put it in constructor but what can I do in static class? Thanks for any ideas.

Durinko
  • 61
  • 4
  • 5
    How about putting it in the [static constructor](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors)? – Sweeper Sep 19 '22 at 06:33

1 Answers1

1

Enums are read-only once you compile. You cannot dynamically extend an enum in runtime. So straight away I say, you cannot do this if your dictionary's key is an enum.

Having said that, and if you are allowed to, your dictionary's key type can be a string, or a number, and based on whatever condition you want, you may add to this static dictionary like you would with any other dictionary. Without more information about the nature of this global value, I cannot go any further.

NOTE you declared your dictionary's key type as SomeStringType, but then tried to add what I imagine is an enum value (someEnum.enum). That does not compile at all. Furthermore, the syntax to initialize a dictionary is not that one. It is [key] = value.

Example:

using System;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        Dictionary<string, string> dic = new Dictionary<string, string>()
        {
            ["a"] = "b",
            ["c"] = "d"
        };
        Console.WriteLine("Count: {0}", dic.Count);
    }
}

So I'm currently unsure if you are having problem with what you explained or if your problem stems from more basic issues, such as an invalid dictionary construction. Please clarify. Thanks a lot.

José Ramírez
  • 872
  • 5
  • 7