Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | Class, Object, Methods

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to check a specified class is an abstra... >>
<< C# program to print constructors of the specified ...