Visual Studio does not see or highlight the box. But in the window with views of the elements of the file it is. Just in case I will throw off the code

public class Constants { public static Dictionary<String, Double> constants = new Dictionary<string, double>(2); constants.Add("PI", Math.PI); } 
  • 6
    this code that you show is invalid and will not be compiled. - tym32167

2 answers 2

You can try this:

 public class Constants { public Dictionary<String, Double> constants = new Dictionary<String, Double>(); public void SetPi() => constants.Add("PI", Math.PI); } public class Program { private static void Main(String[] args) { Constants constant = new Constants(); constant.SetPi(); Console.WriteLine(constant.constants["PI"]); Console.ReadKey(); } } 

Given the comments @ tym32167, you can do this:

 public class Constants { public static Dictionary<String, Double> constants = new Dictionary<String, Double> { { "PI", Math.PI } }; } public class Program { private static void Main(String[] args) { Console.WriteLine(Constants.constants["PI"]); Console.ReadKey(); } } 

Starting from C # 6.0, another initialization method is also available:

 public class Constants { public static Dictionary<String, Double> constants = new Dictionary<String, Double> { ["PI"] = Math.PI }; } 
  • Why this method? Something public - tym32167
  • @ tym32167 to write the value in the dictionary - Yaroslav 6:43 pm
  • Well, I'm in the sense that the class client can do it without a method) - tym32167
  • @ tym32167, I know, it just seemed to me that this was also acceptable - Yaroslav
  • Acceptable of course, I just did not understand your motivation. Now I understand, the question is closed - tym32167

I saw that Visual Studio sees my field in functions and the code below works. But I will look at other options.

 public class Constants { public static Dictionary<String, Double> addConstants() { Dictionary<string, double> constants = new Dictionary<string, double>(); constants.Add("PI", Math.PI); constants.Add("E", Math.E); constants.Add("GOLDEN_RATIO", 1.618); return constants; } private static Dictionary<String, Double> constants = addConstants(); } 
  • and what to be surprised? You have corrected the code and it has earned ... - Pavel Mayorov