I want to access dynamically a static field in a class.
If I were in js, i would do something like this:
Now how do i do it in c#?
You replied to another user that you have code in asp.net where the goal is to be able to be given a value, assume the source of that value, and convert that value into another system.
Your naive solution is to somehow “access dynamically a static field in a class” to solve your problem. You should be aware of a couple of things:
There are many ways to solve this kind of conversion problem
Mashing up keywords like dynamic and static may sound appealing, but ultimately will lead you down a rabbit hole of extremely narrow use cases that have little or nothing to do with your original problem.
So, let’s address your problem rather than your question directly.
Let’s create a class which contains a temperature.
Not a terribly useful class at this point, but it gives us a container to read (and eventually store) a value. But what unit is this temperature in? We don’t know. It doesn’t really matter, to be honest, but at the moment there isn’t one. So let’s assume a few things:
Supported units will be Fahrenheit, Rankine, Celcius, and Kelvin
Internally, we’ll store everything as Fahrenheit. Why? No reason. It’s arbitrary.
Usage:
Output:
Is this the only way to do this? No. Is it the best way? No. Is it the fastest way? No.
But what it does do is answer the question I think you were asking rather than the one you actually wrote.
First, I’d like to ask why. What’s the use case for this. It may be the case where some other technique may be better suited for what you want to do.
Second, if you really need to do this, this is a case for Reflection.
I have this code in asp.net:
Now the problem is I need to set Temperature.Celsius
to Temperature[fromDegree]
so that I can dynamically calculate the temperature. Temperature.Celsius is a static field of Temperature.
https://stackoverflow.com/a/11122523/4739697
But generally I’d say don’t do this if you can avoid it, It’s a bit jank
C# devs
null reference exceptions