TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Reflection Field Example

This C# example program uses reflection on fields in a static class.

Reflection field. With reflection we load field values.

We loop through those fields and display their names and values. System.Reflection, in the .NET Framework, provides a way to enumerate fields and properties. It can access fields by name.

Example. In the .NET Framework, every program is compiled into an assembly containing metadata. This is an abstract binary representation of the program's structure. This improves the options you have when executing your program.

And: You can explore the string data stored in the executable to access field and property names.

Next: This static class has four fields of type Int32 and String. We get the FieldInfo objects for those fields and then display them.

Static ClassInt Type

C# program that uses reflection on fields

using System;
using System.Reflection;

static class ReflectionTest
{
    public static int Height;
    public static int Width;
    public static int Weight;
    public static string Name;

    public static void Write()
    {
	Type type = typeof(ReflectionTest); // Get type pointer
	FieldInfo[] fields = type.GetFields(); // Obtain all fields
	foreach (var field in fields) // Loop through fields
	{
	    string name = field.Name; // Get string name
	    object temp = field.GetValue(null); // Get value
	    if (temp is int) // See if it is an integer.
	    {
		int value = (int)temp;
		Console.Write(name);
		Console.Write(" (int) = ");
		Console.WriteLine(value);
	    }
	    else if (temp is string) // See if it is a string.
	    {
		string value = temp as string;
		Console.Write(name);
		Console.Write(" (string) = ");
		Console.WriteLine(value);
	    }
	}
    }
}

class Program
{
    static void Main()
    {
	ReflectionTest.Height = 100; // Set value
	ReflectionTest.Width = 50; // Set value
	ReflectionTest.Weight = 300; // Set value
	ReflectionTest.Name = "Perl"; // Set value
	ReflectionTest.Write(); // Invoke reflection methods
    }
}

Output

Height (int) = 100
Width (int) = 50
Weight (int) = 300
Name (string) = Perl

This program defines two classes and two methods. The program begins in the Main entry point and the static fields Height, Width, Weight, and Name are assigned on the ReflectionTest static class.

Next: The Write method is invoked. This accesses the Name and GetValue members on each individual FieldInfo.

GetValue method and casting. The syntax used in the ReflectionTest.Write method when calling the GetValue instance method is confusing. In the example, the parameter call be the null literal because it is not used.

IsNull

Note: There may be more elegant ways to obtain the value of a field or property, including adding extension methods.

Extension Method

Discussion. Many programs must maintain a set of preference values that are assigned during startup or later execution. You can store these preferences in an array, but this requires array lookups.

Arrays

Instead: You can loop through fields with reflection and print their values to the console or web page.

Also, this approach improves performance when assigning or reading the values (because they are fields), but is not fast when reflecting the metadata to the screen. You can find more on global variables.

Global Variable

Field instructions. When you use fields (as with stsfld or ldsfld) you are creating exception-free code. The runtime documentation states that reading fields, because it does not invoke executable code, will not throw exceptions.

IL: stsfld, ldsfld

Therefore: You can replace arrays or other collections with fields to improve reliability.

Summary. We invoked the methods in the System.Reflection namespace to enumerate the fields in a class. We examined the syntax and used the typeof operator, the GetFields method, the FieldInfo class, and then the Name and GetValue members.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf