If you already have the class and know nothing about it, and it’s totally dynamic, you really should use reflection, so you can use variables instead of the name. Has a complex example in another answer.
If you are going to create the object and want the same Javascript semantics should use a dictionary instead of a class, after all in JS the object is actually a dictionary. I already answered with an example. Actually in several examples.
If you do not know what you will access then you must use dynamic
, but should avoid whenever possible because C# is not a dynamic typing language. Example.
A final solution. Of course, there are even more complicated solutions.
By the comments I would go from switch
, Extensive code is no justification for using reflection, the code gets absurdly slower. If you don’t want to write the code write a code generator, C# has more and more tools to help with this (in 9 or 10 you will have very interesting features). But if you still insist on not writing the pure code, at least consider the use of a dictionary, by the description of the question and comments is what you need. Almost always reflection is gambiarra.
One last tip: What you want is a field and not the attribute, I know they taught you that way, but they taught you wrong, use the right terminology to avoid confusion.
You will create an attribute in run time and then take its value?
– Barbetta
@Barbetta, no... Attribute names will be stored in an array that was created in time design. In run time, through the index of the array I select from it a string with the name of the desired attribute and "printo" on the screen the contents.
– user75204
Another way I can solve my problem is through if or case for each attribute, but the code would be too extensive.
– user75204