Search code examples
c#reflectionpropertieslitjson

In C#, how do you get the name of an indexed property if you only have it's index number?


I have an object created by a json mapper function (using LitJson). It contains indexed properties.

I can iterate through the properties and get each property value like this

for(int i = 0; i < jdata.Count;i++) {
    Console.WriteLine(jdata[i]);
} 

I would like to get each property name, as a string, rather than the property value.

The closest thing I've found is this https://stackoverflow.com/questions/1011109/how-do-you-get-the-name-of-the-property

Where this works

string name = ReflectionUtility.GetPropertyName((Sample2 s) => s.Foo);

but this doesn't (seemingly because it's an indexed property?)

string name = ReflectionUtility.GetPropertyName((Sample2 s) => s[0]);

Solution

  • I found the source code. Looks like JsonData implements IDictionary, so you should be able to access the Keys property.

    Indexers are implemented basically as functions which take an index argument, so there's no way to use reflection to get a "Name" associated with a given index.