How to Get a List of Properties or Attributes of a Class or Types or Object

Recently I happened to read through all the class properties programmatically I tried multiple ways of identifying to achieve the same including reflection.

So today in this article I’m gonna talk about how to read class properties or attributes programmatically using a simple approach.

I have a simple class as shown below,

 public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string ZipCode { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
        public string EmployeeId { get; set; }
    }

Let’s use the Newtonsoft Nuget package to serialize and deserialize the object for its properties.

Please install it from Nuget Package Manager,

PM> Install-Package Newtonsoft.Json -Version 12.0.3

The below 2-liner did the trick for me!

JObject empJObject = (JObject)JToken.FromObject(empObject);
List<string> dictEmpObject = empJObject.Properties().Select(x => x.Name).ToList();

Below is the complete code,

Get a List of Properties or Attributes of a Class or Types or Object

Please add below using statements,

using Newtonsoft.Json.Linq;
using System.Linq;

Let’s print the result,

That’s All, Happy Coding!

References:



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *