0

I was looking for some time here on stackoverflow to find a method which "converts" a List of strings to a properties - object. Is this possible, and if yes, how do i realize it?

Motivation:

I have a class with let's say 5 features:

classA{
public string feature1 { get; set; };
public string feature2 { get; set; };
public string feature3 { get; set; };
public string feature4 { get; set; };
public string feature5 { get; set; } ;
}

Now, i have a mySQL query and want to only query let's say feature3 and feature5. I saved the query-features in a list of strings. So i have the List of strings:

List<string> fooooo; 
fooooo.Add("feature3");
fooooo.Add("feature5");

I want to iterate over only the features which are in the query, not over all features within the original class.

I tried to realize it after some research with the following function:

public static object GetPropValue( object target, string propName )
 {
     return target.GetType().GetProperty( propName ).GetValue(target, null);
 }

Which resulted in the following Error:

Error: System.NullReferenceException: Object reference not set to an instance of an object.

What's wrong with this function on top?

TL;DR: I want to "translate" a List of strings e.g. "foo1", "foo2" into a properties-object, consisting of the property foo1, and the property foo2.

Thanks already in advance!

beinando
  • 477
  • 4
  • 18
  • And then do what with it? – Caius Jard Jan 17 '22 at 09:49
  • i need it for a front-end output as a tabular with only the queries columns, not all property-columns of the original class – beinando Jan 17 '22 at 09:50
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) Hint: Either your `target` is null, or there is no property with `propName`. In that case, `GetProperty` returns null. – SomeBody Jan 17 '22 at 09:50
  • It is helpful in the context, but not exactly pointing towards my problem. I know i get null-properties out of the function above, but i don't know why. – beinando Jan 17 '22 at 09:53
  • 1
    Using `GetProperty` without specifying any `BindingFlags` is a bad idea. You can use the example of the `GetProperty` overload with `BindingFlags` ([here](https://learn.microsoft.com/en-us/dotnet/api/system.type.getproperty?view=net-6.0#system-type-getproperty(system-string-system-reflection-bindingflags))). [Here](https://dotnetfiddle.net/UEVoZ8) is a fiddle demonstrating that it works – MindSwipe Jan 17 '22 at 09:59

0 Answers0