C# - Print Properties of a Class Using PropertyInfo

Learn, how to print properties of the specified class using PropertyInfo class in C#?
Submitted by Nidhi, on October 28, 2020 [Last updated : March 22, 2023]

Here, we will print properties of the specified class using the predefined reflection class PropertyInfo, here we need to import the System.Reflection namespace in the program.

C# program to print properties of the specified class using PropertyInfo class

The source code to print properties of the specified class using PropertyInfo class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to print properties of the specified class 
//using PropertyInfo class

using System;
using System.Reflection;

class Student
{
    int id;
    string name;

    public int Id
    {
        get { return id; }
        set { id = value; }
    }

    public string Name   
    {
        get { return name; }   
        set { name = value; }  
    }
}

class Program
{
    static void Main()
    {
        Type type = typeof(Student);

        Console.WriteLine("Properties of Student class:");
        PropertyInfo[] properties = type.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine("\t"+property);
        }  
    }
}

Output

Properties of Student class:
        Int32 Id
        System.String Name
Press any key to continue . . .

Explanation

In the above program, we created two classes Student and Program. Here, we imported the System.Reflection to use Assembly class.

The Program class contains the static method Main(), the Main() method is the entry point for the program.

Here, we created reference type of Type class which is initialized with type returned by typeof() operator, here we passed class Student in the typeof() operator, and then we got the properties using the GetProperties() method and then accessed the properties using foreach loop one by one and printed on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.