How to convert PropertyInfo[] to my class

916 Views Asked by At

I'm developing an .NET Core 3.1 API, and I had a situation where I needed to iterate an object using foreach. To be able to do this, I used Reflection:

var properties = myClass.GetType().GetProperties();

After that, the code goes through the foreach as normal, and then I return the modified properties object to an external API, but it returns a timeout error message, I think it is because the PropertyInfo[] class isn't very appropriate for returning like this, or it's something else, I don't know.

Because of that, I want to convert properties "back" to myClass, or maybe convert it into an dictionary, it would be better to return the original class instead of PropertyInfo[].

How can I convert PropertyInfo[] into a class?

Thanks!

1

There are 1 best solutions below

0
Peter Dowdy On BEST ANSWER

It sounds like you're trying to serialize this class to send to an API. What format does your API accept? If it accepts e.g. json, you should just use a json serializer (like JSON.net - which uses things like reflection under the hood anyways). If you are trying to serialize to a more exotic or unsupported format, then you can do it this way. What's missing is that the Properties[] array doesn't contain the values of your properties, only the definition. You can use the properties array to fetch the values:

public class MyClass
{
    public int a { get; set;}
    public string b {get; set; }
}

void Main()
{
    var instance = new MyClass{a=1,b="2"};
    var properties = instance.GetType().GetProperties();
    var value_of_a = properties.First(p => p.Name == "a").GetValue(instance);
}

Each property has a "GetValue" method on it that can extract the value corresponding to that property from the class the property came from - note that up above you call 'GetType()' before you call 'GetProperties' - this means you're getting properties for the Type, not the instance. You then need to take those property definitions back to the instance to get the property values.