Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an object's property by name lookup?

I worked a lot in ActionScript and I was pleased to see that it is very similar to C#, but there's one thing that I'm missing, and that is "dynamic referencing".

For example, dynamic referencing can be done using the array operator[]. So for instance you could also access the property some_thing.something_else in the following two ways:

some_thing["something_else"]
// or

some_thing[some_var] // where some_var is a variable holding a string
// e.g.: some_var = "something_else";

In other words, the array syntax is equivalent to specifying the property itself.

The other option to reference an object dynamically is using the eval() global function.

So, my question: Is it possible to reference properties in C# in a manner similar to ActionScript?

like image 994
IneedHelp Avatar asked Sep 03 '25 10:09

IneedHelp


2 Answers

The only way I can see to do this would be using dynamics, and in particular the ExpandoObject. With the ExpandoObject class you can do things like:

dynamic employee;

employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;

Despite employee not having any of those properties on it, this code will compile and work. Not only will it work, but dynamic properties are even strongly typed.

Accessing properties by key is also easy. ExpandoObject implements IDictionary<string,object>, so its as simple as a downcast:

var dictEmployee = employee as IDictionary<string,object>;
Debug.WriteLine(dictEmployee["Age"].ToString);

This code will result in 33 being printed into the debug output.

I wouldn't suggest using this method pervasively, but it comes in handy on occasion.

like image 193
nathan gonzalez Avatar answered Sep 05 '25 00:09

nathan gonzalez


There's no eval in C#.

Regarding first part of your question. While following is perfectly possible in C#

var key = "ouch";
Console.WriteLine(something[key]);

there're two things worth mentioning.

  1. there's nothing dynamic about this code, at least in the C# meaning of dynamic
  2. something is not an array, but dictionary.
like image 22
Serg Rogovtsev Avatar answered Sep 05 '25 01:09

Serg Rogovtsev