Use reflection to list SystemInformation properties in C#


[reflection]

This example shows how you can use reflection to get the properties defined by the SystemInformation class.

The SystemInformation class is chock-full of useful properties that give information about system parameters. These include such values as the thickness of a text caret, the size of menu buttons, the default font, and the name of the computer. The example Use reflection to list a class’s properties in C# explains how to list a class’s properties. This example uses the reflection techniques explained in that post to explore the SystemInformation class and list its properties and their values.

When the program’s form loads, the following code displays information about the class’s properties.

// List the SystemInformation class's properties.
object property_value;
PropertyInfo[] property_infos =
    typeof(SystemInformation).GetProperties(
        BindingFlags.FlattenHierarchy |
        BindingFlags.Instance |
        BindingFlags.NonPublic |
        BindingFlags.Public |
        BindingFlags.Static);
foreach (PropertyInfo info in property_infos)
{
    string name = info.Name;
    string value = "";

    // See if it's an array.
    if (!info.PropertyType.IsArray)
    {
        // It's not an array.
        if (info.CanRead) property_value =
            info.GetValue(this, null);
        else property_value = "---";

        if (property_value == null)
            value = "<null>";
        else
            value = property_value.ToString();
    }
    else
    {
        // It is an array.
        name += "[]";
        value = "lt;array>";
    }

    ListViewMakeRow(lvwProperties, name, value);
}

The code gets the SystemInformation class’s type and calls its GetProperties method to get information about the class’s properties. See the example Use reflection to list a class’s properties in C# for information about the BindingFlags parameters.

The code then loops through the PropertyInfo objects that GetProperties returns. The code gets the properties’ names and values, and calls the ListViewMakeRow method to display the information in the form’s ListView control. Download the example program to see how the ListViewMakeRow method works and for other details.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in reflection and tagged , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Use reflection to list SystemInformation properties in C#

  1. Richard Moss says:

    Serenity? You’re not a fan of Firefly by any chance?

    [Totally off topic but I saw the name and was amused :)]

  2. Rod Stephens says:

    Maybe ?

    And it seems like a good name for a computer, doesn’t it?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.