Global dictionary & partial class scheme - error: cannot be accessed with an instance reference
-
I'd like to have a globals class in my app with a global dictionary, but am having trouble getting past the error below. Any ideas or suggestions?
using System; using System.Collections.Generic; namespace GlobalDict { public partial class Globals { public static Dictionary<string, int> GlobalInts = new Dictionary<string, int>() { {"one", 1}, {"two", 2}, }; } class Program { public static Globals g = new Globals(); static void Main(string[] args) { int i = g.GlobalInts["two"]; /* Error: Member 'GlobalDict.Globals.GlobalInts' * cannot be accessed with an instance reference; * qualify it with a type name instead */ } } }
Sincerely, -Ron
-
I'd like to have a globals class in my app with a global dictionary, but am having trouble getting past the error below. Any ideas or suggestions?
using System; using System.Collections.Generic; namespace GlobalDict { public partial class Globals { public static Dictionary<string, int> GlobalInts = new Dictionary<string, int>() { {"one", 1}, {"two", 2}, }; } class Program { public static Globals g = new Globals(); static void Main(string[] args) { int i = g.GlobalInts["two"]; /* Error: Member 'GlobalDict.Globals.GlobalInts' * cannot be accessed with an instance reference; * qualify it with a type name instead */ } } }
Sincerely, -Ron
Aside from warning you about using globals AND public members, you can't use an instance. Try this syntax:
Globals.GlobalInts["two"];
If you remove the static modifier, you'll be able to use the instance reference. Scott P“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.” -Edsger Dijkstra