-3

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
    I have a feeling your problem isn't what you think it is though I agree you shouldn't return `PropertyInfo[]`. We need more code context. Timeout is sometimes because of misuse of async/await. – Crowcoder Jun 11 '21 at 15:25
  • In my code I'm not using async/await, their is not much to show in my code, I guess I was to vague in what I asked, my question is just how can I convert PropertyInfo[] into to a class. – Matheus Souza Silva Jun 11 '21 at 15:44
  • Can you paste your code that's causing the problem? – sr28 Jun 11 '21 at 17:26

1 Answers1

0

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.

Peter Dowdy
  • 439
  • 2
  • 16