Introduction to Reflection
Obtain information on types while the program is running.
We'll cover the following
Introduction
Every application is composed of classes and other types, as well as their methods, properties, indexers, and so on. Reflection lets us obtain type information while the program is running. For instance, we could discover what methods a class has, what properties it operates, and what interfaces it implements. Reflection is type discovery at runtime.
The reflective functionality of .NET is located in the System.Reflection
namespace. To obtain information on a type, we use the System.Type
class. This class has methods like:
-
GetMembers()
: This returns aMemberInfo[]
object. -
GetConstructors()
: This returns aConstructorInfo[]
object. -
GetMethods()
: This returns information onMethodInfo[]
methods.
These are only a handful of the members exposed by the Type
class. The list is much longer, but the methods mentioned here provide a general idea about the Type
class.
Obtain type information
To obtain information on a type, we must first get an instance of the Type
class that’s related to the type we’re interested in. We can do that in three ways:
-
Use the
typeof
operator -
Call the
GetType()
on a type we’re interested in -
Call the static
Type.GetType()
method and provide the name of the type
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy