C#

C# Reflection Introduction

Reflection in C# is a big topic in itself. I’ll summarize a little list of what you can do with reflection.

  1. Get currently executing assembly, load assembly, get assembly from type
  2. Get classes declared in assemblies
  3. Get methods, properties, fields, events, constructors declared in classes
  4. Check access modifiers of classes, properties, fields and methods
  5. Get nested classes in a class
  6. Get base type of a class
  7. Create an instance of a class at runtime, get and set properties and invoke methods with parameters.

.NET assembly is a collection of types and its metadata. Metadata describes all the types and its structures like methods, fields, events, and properties. Metadata also defines all the attributes defined in assemblies.

Reflection Namespaces

For using the .NET Reflection, you have to include two main namespaces.

  1. System
  2. System.Reflection

System provides the Type class. A Type class stands for class types, interface types, array types, value types, enum types, type parameters, generic type definitions, and open/closed generic types.

Type provides very useful properties and methods to obtain information about types.

  • Assembly
  • IsAbstract
  • IsArray
  • IsClass
  • IsGenericParameter
  • IsGenericTypeDefinition
  • IsInterface
  • IsNested
  • IsPublic
  • IsNotPublic
  • IsValueType
  • ?GetConstructors
  • GetInterface
  • GetMembers
  • GetMethods
  • GetProperties

System.Reflection contains important classes for getting the types and its information in Assemblies. Some important classes are:

  1. Assembly
  2. ConstructorInfo
  3. EventInfo
  4. FieldInfo
  5. MemberInfo
  6. MethodInfo
  7. ParameterInfo
  8. PropertyInfo
  9. TypeInfo

I have explained all the namespaces required for using C# reflection. In the next sessions, I’ll explain how to use above classes and some examples of them.