How to get a list of class properties in C#? Getting property names and types via reflection
Hello everyone! I just started learning C# and encountered a task: I need to programmatically get a list of all properties of some class, for example, to output their names and types to the console or save them to a file. Let's say I have a class like this:
```csharp
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
private string secret; // this is a field, not a property
}
```
I want to get something like this as output:
- Name: string
- Age: int
- City: string
I've heard that reflection is used for this, but I don't understand how to apply it exactly. I tried googling, but found many different options — with GetProperties(), BindingFlags, etc. Please tell me the simplest and correct way.
No answers yet.
Log in to leave an answer
Blogs