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?
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.
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.
something
is not an array, but dictionary.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