Lets say I have the following class:
public class Provider
{
...
public sealed class Slice
{
public readonly double firstName;
public readonly double secondName;
public readonly double thirdName;
...
}
...
}
This class is used to hold a sliding time series and the contained Slice class is the return value. (Provider.Last property returns the latest instance of Slice).
I need to get the value of the properties of that latest returned Slice class by name of the property.
PropertyInfo secondNameProperty = Provider.Last.GetType().GetProperty("secondName");
double secondNameValue = (double)secondNameProperty.GetValue(Provider.Last, null);
GetProperty returns null. How can I do this?
Look at your
Sliceclass:Those aren’t properties. They’re fields. Either make them properties, or use
Type.GetField()instead. Using properties would generally be a better idea, IMO, and needn’t be hard. For example, if you just wanted to make them publicly read-only, you could use:Alternatively you could declare read-only fields directly, and then expose them via properties. It’s a bit more work than using automatically implemented properties, but it removes the potential for setting the property within
Sliceitself.(As an aside, do you really have a
firstNamefield of typedouble? Odd.)