Looks like this has been answered for python, but not C#, and since I’m python illiterate and new at C#, here goes:
I’m trying to get a property from a instance of a class (Task/task) based on a enum parameter (type) and add the property to a List. The tricky part is that I’m not sure if the property value is going to be a string or a list of strings.
So, generally I’m looking at something like:
PropertyInfo propertyInfo = typeof(Task).GetProperty(type.ToString());
List<string> values = new List<string>();
then something I know doesn’t work when the value is a List, but illustrates my intent:
values.Add((string)propertyInfo.GetValue(task, null));
What are my options?
You can use
PropertyInfo.PropertyTypeto check the type of the property – or you could just fetch the value asobjectand go from there:Or instead of using
isand casting, you can useasand check the result against null:Note that this works if the property is any other sort of sequence of strings, not just a
List<string>. It also copies the list, so that any further changes won’t affect the existing list that the property refers to. Adjust if you need to 🙂One point that Lee’s answer reminded me of – if it’s a
stringproperty with anullvalue and you want a list with a single null element, you’ll need to usePropertyType. For example: