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

Here, we are going to learn how to print properties of the specified class using PropertyInfo class in C#?
Submitted by Nidhi, on October 28, 2020

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.

Program:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.