Using GetProperties() in C#

Reflection, in the simple terms, is the ability to extract information about an object during runtime. I found a great explanation of why Reflection is used in a tutorial titled Reflection in C#.

With reflection we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If Attributes (C#) are used in application, then with help of reflection we can access these attributes. It can be even used to emit Intermediate Language code dynamically so that the generated code can be executed directly.

I have been doing some research and test apps using the GetProperties method. GetProperties basically returns array of PropertyInfo objects.

Sample Program

using System;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        var person = new Person
        {
            Name = "Rhonda",
            FaveShow = "Fringe, Lost",
            FaveMovie = "Star Trek",
            FaveSong = "Contagious"
        };

        var type = typeof(Person);
        var properties = type.GetProperties();

        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine("{0} : {1}", 
                             property.Name, property.GetValue(person, null));
        }

        Console.Read();
    }
}

public class Person
{
    public string Name { get; set; }
    public string FaveShow { get; set; }
    public string FaveMovie { get; set; }
    public string FaveSong { get; set; }
}

C# Listing on GitHub 

As you can see below there are several other methods available as well as GetProperties.

Reflection1

 

Output

Reflection2

 

Additional Information

^..^

Posted on February 28, 2010, in .NET General, C#. Bookmark the permalink. 2 Comments.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.