Get the list of all properties of a class in C#


Today we got a requirement to get the list of all the properties of a class including the values.

Here is a C# code for it.

class Customer

     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string MiddleName { get; set; }

class Program

     static void Main(string[] args)
         // Creating an object for a class
         Customer objCustomer = newCustomer();
         objCustomer.FirstName = “John”;
         objCustomer.LastName = “Hung”;
         objCustomer.MiddleName = “Maro”;

         // Reading the properties and displaying the Name and Value.

         foreach (var prop inobjCustomer.GetType().GetProperties())
             Console.WriteLine(“{0} = {1}”, prop.Name, prop.GetValue(objCustomer, null));

Hope this helps.

Happy Coding


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s