I'm using Dictionary<string, string>
as configuration for instruments, and it'd be easier for my users who don't know a lot about programming to be able to get autocomplete from Visual Studio.
In Python I can make a Dictionary and access the different values with a dot operator.
d = {'name':'Joe', 'mood':'grumpy'}
d.name
d.mood
Does C# have a way to do this?
I realize all of the problems involved since dictionary is a just a generic collection (how generic? is it just a list of KeyValuePairs? interesting question). I'm not about to write a wrapper class for this to accomplish it (I'd like it to be a bit more flexible than using explicit properties with a custom class).
Switching to Python, bad news : dot notation is not directly available with the resulting dictionary.
Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property. Example: var cat = { name: 'Moo', age: 5, }; console.
Dot notation indicates that you're accessing data or behaviors for a particular object type. When you use dot notation, you indicate to Python that you want to either run a particular operation on, or to access a particular property of, an object type.
We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .
You can already do that in C# with anonymous types:
var d = new { name = "Joe", mood = "grumpy"};
d.name
d.mood
Or real types:
var d = new Person { Name = "Joe", Mood = "grumpy"};
d.Name
d.Mood
And, in C# 4.0 we will have the DLR which will allow adding properties at runtime using the ExpandoObject:
dynamic d = new ExpandoObject();
d.name = "Joe";
d.mood = "grumpy";
However, I'm not sure that you can do IntelliSense using static analysis in C#.
The closest C# equivalent to what you have is
var d = new Dictionary<string, string>()
{ { "name", "Joe" }, { "mood", "grumpy" } };
d["name"]
d["mood"]
Which will not support IntelliSense.
If you are making an API, I would use real types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With