PHP Variables in .NET.

Does .NET support something similar to PHP's variable variables ?

If not, how 1 could such a function be implemented?


1 If you think that variable variables are always bad, feel free to state your case, but the main question is: how can they be implemented?

+2


source to share


4 answers


This is a feature deeply embedded in dynamic languages . C # has its roots as a static, object-oriented language, and prior to C # 3.0, that meant you weren't going to be able to achieve what you want in any correct way. However, C # 4.0 / .NET 4.0 introduces a keyword dynamic

that allows you to dynamically inject variables like in PHP. Unfortunately, while this is a step forward towards C # becoming a static / dynamic hybrid language, it lacks a key feature eval

that almost every dynamic language has. With a common compiler feature as a C # 5.0 / .NET 5.0 service, this will be effectively introduced (although the internal behavior will not be the same). Until then, there is no decent solution other than a hack with Dictionary

to store variable names.



+1


source


Why not just use a dictionary?

Dictionary<string,string> stuffHash = new Dictionary<string,string>();

string varname = "TheNameOfTheVar";
string value = "foo";

stuffHash[varname] = value;

      



There is no need to do this ugly thing.

+6


source


.Net does not support "variable variables" natively - probably mainly because it is a [strongly typed language] [1].

However, it does support dynamic type instantiation at runtime, which can be used to perform similar actions as PHP variable variables.

+3


source


No, none of the .NET languages โ€‹โ€‹support anything like this. This could be implemented by one of the compiler commands, but I doubt they will.

As for how this can be implemented by you (and not by a C # compiler command), it would be to store all the variables as a variable in Dictionary<String,Object>

- this would allow you to link the string to the object.

I never really understood what problem is solved by variables (in other words, I never heard of a good argument for using them). I would be interested to see an example where they were needed, as I would imagine that it would not be easy to find a better approach to solving the problem without variable variables.

+1


source







All Articles