Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use dot notation for accessing dictionary values?

Tags:

c#

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).

like image 868
Oren Mazor Avatar asked Feb 08 '10 16:02

Oren Mazor


People also ask

Can I access Python dictionary with dot?

Switching to Python, bad news : dot notation is not directly available with the resulting dictionary.

What is dot notation used for?

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.

What is dot notation used for in Python?

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.

What type of object Cannot be used as keys in dictionary?

We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .


1 Answers

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.

like image 123
John Gietzen Avatar answered Nov 15 '22 10:11

John Gietzen