C# Reflection Property Program

This C# example uses reflection on instance properties. It requires System.Reflection.

Reflection property. A program uses properties.

 The reflection mechanism can get the values of these properties. We loop over the instance properties and determine their values. With reflection a property can be referenced by a string identifier.

Based on:

.NET 4.5

 

 

Example. To begin, this program uses the System.Reflection namespace. The Program class has two instance properties: the Awesome property and the Perls property. One is of type int and the second is of type string.

Int

 

Here: In the Main entry point, we create an instance of Program and assign the properties.

C# program that uses reflection on properties

using System;
using System.Reflection;

class Program
{
    public int Awesome { get; set; }
    public string Perls { get; set; }

    static void Main()
    {
	// Create an instance of Program.
	Program programInstance = new Program();
	programInstance.Awesome = 7;
	programInstance.Perls = "Hello";

	// Get type.
	Type type = typeof(Program);

	// Loop over properties.
	foreach (PropertyInfo propertyInfo in type.GetProperties())
	{
	    // Get name.
	    string name = propertyInfo.Name;

	    // Get value on the target instance.
	    object value = propertyInfo.GetValue(programInstance, null);

	    // Test value type.
	    if (value is int)
	    {
		Console.WriteLine("Int: {0} = {1}", name, value);
	    }
	    else if (value is string)
	    {
		Console.WriteLine("String: {0} = {1}", name, value);
	    }
	}
    }
}

Output

Int: Awesome = 7
String: Perls = Hello

Reflection code. Next, we use the reflection mechanisms to get the value of all of the properties. We evaluate the typeof(Program) and then call GetProperties() on the Type returned.

TypeofType

Next: On the PropertyInfo type in the foreach-loop, we use the Name property and also the GetValue method.

Foreach

The call to GetValue is interesting because it requires the instance of the object we are searching. If you are using a static type, you can just pass null. Here we pass the programInstance variable we instantiated earlier.

Casting the object. The GetValue method returns an object, which is the base type of the more derived types int and string. We use the is-cast to determine which we have, and then print custom messages to the Console.

IsConsole.WriteLineConsole

 

Summary. The reflection mechanism in the .NET Framework and C# language is a powerful way of dealing with program data. Your program actually becomes a database, which you can create methods to search and mutate values.

 

Thus: The program becomes mutable data and can be accessed and manipulated by itself.