Reflection. Examples of obtaining information about methods, interfaces, classes, structures, enumerations, delegates, type fields, method parameters, type statistics
Contents
- 1. What using of System.Type.GetType() method?
- 2. What means the reflection of methods? How to get information about the methods? An example of methods reflection
- 3. How to get information about fields of a class, structure or enumeration? Examples of reflection of fields and properties
- 4. How to get information about the interfaces that the class implements? An example of interfaces reflection
- 5. An example of using reflection to obtain additional information about the type (class, structure, enumeration)
- 6. How to get information about the properties of a class? Example
- 7. An example of using reflection to get information about method parameters
- Related topics
Search other websites:
1. What using of System.Type.GetType() method?
The System.Type.GetType() method is used to get an instance of the type specified by the parameter. The parameter of method is a string type. The parameter specifies the name of the type for which you want to get information. In general, the System.Type.GetType() method has 7 overloaded implementations.
To get a list of methods of a certain type (for example, a class), you must first obtain an object containing information about the type. This is done using the method
GetType("NameSpace.TypeName").
where
- NameSpace – the name of the namespace in which the type named TypeName is located that needs to be investigated;
- TypeName – the name of the type for which you want to receive information. The type can be a class, structure, interface, enumeration, delegate.
For example
Type tp = Type.GetType("Dates.Date");
In this example, you need to create an instance (object) named tp, containing information about the type named Date, which is declared in the Dates namespace.
⇑
2. What means the reflection of methods? How to get information about the methods? An example of methods reflection
Reflection of methods allows to obtain information about the list of public methods of a given type. Information about methods can be obtained for a class, structure, or interface. Only these types can contain method declarations.
To get the list of methods of a given type instance, you need to call the GetMethods() method, which returns an array of type MethodInfo, which contains all the necessary information about the methods.
Example. The Date class is specified, which defines the date. The class has 3 internal variables and 6 access methods. The text of the program, which demonstrates the reflection of methods is below. The program is created using the Console Application template.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // include the System.Reflection namespace using System.Reflection; namespace ConsoleApp2 { // class, which defines a date public class Date { int number; int month; int year; // access methods public int GetNumber() { return number; } public int GetMonth() { return month; } public int GetYear() { return year; } public void SetNumber(int nnumber) { number = nnumber; } public void SetMonth(int nmonth) { month = nmonth; } public void SetYear(int nyear) { year = nyear; } } class Program { static void Main(string[] args) { // get information about methods // get an instance of the type by its name Type tp = Type.GetType("ConsoleApp2.Date"); // class name "Date" in the assembly ConsoleApp2 // get an array of class Date methods MethodInfo[] methods = tp.GetMethods(); // display the method names int i = 0; foreach (MethodInfo mi in methods) { i++; Console.WriteLine("Method[{0}] = {1}", i, mi.Name); } } } }
As a result of this code execution, a list of method names will be displayed, which are available for any object of the Date class:
Method[1] = GetNumber Method[2] = GetMonth Method[3] = GetYear Method[4] = SetNumber Method[5] = SetMonth Method[6] = SetYear Method[7] = ToString Method[8] = Equals Method[9] = GetHashCode Method[10] = GetType Press any key to continue . . .
The following should be noted:
- information can be obtained only about those methods that are declared publicly available with the public access modifier;
- to get an instance of a type using the GetType() method from the static Main() function, first you must specify the name of the namespace in which this class is implemented.
⇑
3. How to get information about fields of a class, structure or enumeration? Examples of reflection of fields and properties
To get information about a field (property) of a particular type (class, structure, enumeration), you need to use the Type.GetFields() method. This method returns an array of type FieldInfo. The FieldInfo type contains all the necessary information about the fields and properties that are declared as public.
Example 1. Getting information about structure fields. The Worker structure is given. The structure has 3 fields with the names name, age, rank. The example demonstrates the output of information about the name of the field and its type (the FieldType property). The example is implemented as a console application.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // include the System.Reflection namespace using System.Reflection; namespace TrainReflection { // structure that implements employee information public struct Worker { public static string name; // name of worker public int age; // employee age public float rank; // ranking } class Program { static void Main(string[] args) { // get information about the Worker structure fields // create an object that contains information about the Worker structure Type tp = Type.GetType("TrainReflection.Worker"); // get information about the Worker structure fields FieldInfo[] fields = tp.GetFields(); // display the field names, their types and some attributes int i = 0; string nameType; foreach (var field in fields) { i++; nameType = field.FieldType.ToString(); // get the name of the field type of structure Worker Console.Write("Field[{0}] = {1}, type = {2}", i, field.Name, nameType); // check if the field static if (field.IsStatic) Console.Write(", static"); // checking, is the field declared as public? if (field.IsPublic) Console.Write(", public"); Console.WriteLine(); } } } }
As a result, the following text will be displayed:
Field[1] = age, type = System.Int32, public Field[2] = rank, type = System.Single, public Field[3] = name, type = System.String, static, public Press any key to continue . . .
In the same way, you can get information about the fields of any class of any assembly. It is enough to know only the name of the class in the assembly.
Example 2. Retrieving information about fields of enumeration. A Month enumeration is specified. It implements the abbreviated names of the months of the year. The following is an example of obtaining information about enumeration based on information about its name.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // include the System.Reflection namespace using System.Reflection; namespace TrainReflection { // a enumeration that implements information about the month of the year enum Month { Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec } class Program { static void Main(string[] args) { // get information about the fields listed in the month // create an object that contains information about the Worker structure Type tp = Type.GetType("TrainReflection.Month"); // get information about the fields in the Month enumeration FieldInfo[] fields = tp.GetFields(); // display the names of enumeration int i = 0; string value; foreach (var field in fields) { i++; Console.WriteLine("Field[{0}] = {1}", i, field.Name); } } } }
As a result, the following text will be displayed.
Field[1] = value__ Field[2] = Jan Field[3] = Feb Field[4] = Mar Field[5] = Apr Field[6] = May Field[7] = Jun Field[8] = Jul Field[9] = Aug Field[10] = Sep Field[11] = Oct Field[12] = Nov Field[13] = Dec Press any key to continue . . .
⇑
4. How to get information about the interfaces that the class implements? An example of interfaces reflection
To get a list of interface names that are supported by a given type, use the GetInterfaces() method. This method returns an array of interfaces of Type[] type. The name of the interface is placed in the Name property.
Example. Let an IDate interface be defined in which two methods are declared: GetNumber(), SetNumber(). A Date class is also declared that implements the date. The Date class inherits the IDate interface. In the example is shown:
- getting a list of interfaces of the Date class;
- getting a list of methods of IDate interface.
Full listing of the program that demonstrates this example.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // include the System.Reflection namespace using System.Reflection; namespace TrainReflection { // interface with two declared methods interface IDate { int GetNumber(); void SetNumber(int nnumber); } // the class that implements the date - inherits the IDate interface public class Date:IDate { int number; int month; int year; // accesss methods public int GetNumber() { return number; } public int GetMonth() { return month; } public int GetYear() { return year; } public void SetNumber(int nnumber) { number = nnumber; } public void SetMonth(int nmonth) { month = nmonth; } public void SetYear(int nyear) { year = nyear; } } class Program { static void Main(string[] args) { // get information about methods // get an instance of the type by its name Type tp = Type.GetType("TrainReflection.Date"); // class name - "Date" // get the array of interfaces of class Date Type[] interfaces = tp.GetInterfaces(); // display the names of interfaces on the screen int i = 0; foreach (Type t in interfaces) { i++; Console.WriteLine("Interface[{0}] = {1}", i, t.Name); } Console.WriteLine(); // create an object that contains information about the IDate interface Type tpi = Type.GetType("TrainReflection.IDate"); // get an array of methods for the IDate interface using the tpi object MethodInfo[] methods = tpi.GetMethods(); // display a list of methods of IDate interface i = 0; foreach (MethodInfo mt in methods) { i++; // display the full name of each interface method Console.WriteLine("Method[{0}] = {1}", i, mt.Name); } } } }
As a result of the program execution, the following will be displayed:
Interface[1] = IDate Method[1] = GetNumber Method[2] = SetNumber Press any key to continue . . .
⇑
5. An example of using reflection to obtain additional information about the type (class, structure, enumeration)
Using the reflection, you can get additional information about the type. The type can be a class, structure, interface, enumeration, delegate.
Example. Let two classes be given:
- class Point, which implements a point on the coordinate plane;
- class Pixel that implements a point of a given color. The Pixel class inherits from the Point class. Below is the full text of the program, which displays additional information about the Point and Pixel classes. The program is implemented as an application of the Console Application type.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // include System.Reflection namespace using System.Reflection; namespace TrainReflection { public class Point { // internal variables of class protected int x; protected int y; // access methods public void GetXY(out int xx, out int yy) { xx = x; yy = y; } public void SetXY(int xx, int yy) { x = xx; y = yy; } } // class Pixel is derived from Point class sealed class Pixel:Point { // internal variable color int color; // access methods public void GetXYC(out int xx, out int yy, out int cl) { GetXY(out xx, out yy); cl = color; } public void SetXYC(int xx, int yy, int cl) { SetXY(xx, yy); color = cl; } } class Program { static void Main(string[] args) { // create objects for Point and Pixel classes Type tPoint = Type.GetType("TrainReflection.Point"); Type tPixel = Type.GetType("TrainReflection.Pixel"); // display some information about the class Point Console.WriteLine("Information about Point class:"); if (tPoint.IsAbstract) Console.WriteLine("Abstract class"); // abstract class if (tPoint.IsArray) Console.WriteLine("Array"); // is an array if (tPoint.IsClass) Console.WriteLine("Class or delegate"); // is class or delegate if (tPoint.IsEnum) Console.WriteLine("Enumeration"); // is enumeration if (tPoint.IsInterface) Console.WriteLine("Interface"); // is interface if (tPoint.IsPublic) Console.WriteLine("Public"); // is declared as public if (tPoint.IsSealed) Console.WriteLine("Sealed"); // is sealed Console.WriteLine(); // display some information about the Pixel class Console.WriteLine("Information about Pixel class:"); if (tPixel.IsAbstract) Console.WriteLine("Abstract class"); // abstract class if (tPixel.IsArray) Console.WriteLine("Array"); // it is an array if (tPixel.IsClass) Console.WriteLine("Class or delegate"); // it is class or delegate if (tPixel.IsEnum) Console.WriteLine("Enumeration"); // is enumeration if (tPixel.IsInterface) Console.WriteLine("Interface"); // is interface if (tPixel.IsPublic) Console.WriteLine("Public"); // is declared as public if (tPixel.IsSealed) Console.WriteLine("Sealed"); // is sealed } } }
As a result of the program, the following will be displayed:
Information about Point class: Class or delegate Public Information about Pixel class: Class or delegate Sealed Press any key to continue . . .
⇑
6. How to get information about the properties of a class? Example
To get information about the properties of a class, call the GetProperties() method. This method returns an array of type PropertyInfo[].The PropertyInfo[] array contains information about the properties of a class.
Example. Demonstrated receiving a list of properties for the Student class from the TrainReflection namespace. Properties must be declared with the public access modifier.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // include System.Reflection namespace using System.Reflection; namespace TrainReflection { // information about student class Student { string name; // student name string numBook; // number of gradebook float rank; // ranking of student // properties public string Name { get { return name; } set { name = value; } } public string NumBook { get { return numBook; } set { numBook = value; } } public float Rank { get { return rank; } set { rank = value; } } } class Program { static void Main(string[] args) { // get information about properties from the Student class // get an object of type System.Type Type tp = Type.GetType("TrainReflection.Student"); // get a list of properties PropertyInfo[] properties = tp.GetProperties(); // display property list int i = 0; foreach (PropertyInfo p in properties) { i++; Console.WriteLine("Property[{0}] = {1}", i, p.Name); } } } }
On the screen the following text will be displayed
Property[1] = Name Property[2] = NumBook Property[3] = Rank Press any key to continue . . .
⇑
7. An example of using reflection to get information about method parameters
For a specific method, you can get information about its parameters.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // include System.Reflection namespace using System.Reflection; namespace TrainReflection { // class that contains math functions class MathFunctions { // method that solves quadratic equation public bool CalcEquation(double a, double b, double c, out double x1, out double x2) { double d = b * b - 4 * a * c; if (a==0) { if (b==0) { x1 = x2 = 0; return false; } else { x1 = x2 = -c / b; return true; } } if (d<0) { x1 = x2 = 0; return false; } x1 = (-b - Math.Sqrt(d)) / (2 * a); x2 = (-b + Math.Sqrt(d)) / (2 * a); return true; } } class Program { static void Main(string[] args) { // get information about properties of Student class // get the object of System.Type type Type tp = Type.GetType("TrainReflection.MathFunctions"); // get an object that contains information about the specific CalcEquation method of the MathFunctions class MethodInfo method = tp.GetMethod("CalcEquation"); // get the CalcEquation method parameters ParameterInfo[] parameters = method.GetParameters(); // display the parameters of method Console.WriteLine("Parameters of method CalcEquation:"); int i = 0; foreach (ParameterInfo p in parameters) { i++; Console.WriteLine("Parameter[{0}] = {1} of type {2}", i, p.Name, p.ParameterType.Name); } // display the type of the value returned by the method string returnType = method.ReturnType.FullName; Console.WriteLine(); Console.WriteLine("The returned type: {0}", returnType); } } }
The output will be as follows.
Parameters of method CalcEquation: Parameter[1] = a of type Double Parameter[2] = b of type Double Parameter[3] = c of type Double Parameter[4] = x1 of type Double& Parameter[5] = x2 of type Double& The returned type: System.Boolean Press any key to continue . . .
⇑
Related topics
- Run-time type information (RTTI). Statements is, as. Examples
- Reflection of types. Getting type metadata. The System.Reflection namespace. Class System.Type. Ways to get information about types
- Dynamically loadable assemblies. Class Assembly. Methods Load() and LoadFrom()