Reflection in c with example LEARNOVITA

What is Reflection in C#? | Learn Now Tutorial

Last updated on 16th Aug 2022, Blog, Tutorials

About author

Madhuri (C# Automation Tester )

Madhuri is a C# Automation Tester and She has tons of experience in the areas of HTTP, SOAP/REST, VisualStudio, TFS, etc., CI/CD, functional, regression, and .NET technology stack. She spends most of her time researching technology, and startups.

(5.0) | 18575 Ratings 2096

C# – Reflection example

Reflection objects are used for obtaining type information at the runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace. The System.Reflection namespace contains classes that permit to obtain information about the application and to dynamically add types, values, and objects to the application.

What is Programming Reflection?

Reflection can offer information about the assemblies that have been loaded and metadata about types declared in them. The metadata information on a type is made accessible by the Type abstract class Reflection in C# is like native RTTI (Runtime Type Information) of C++, there is a significant difference: reflection in C# works only with maintaining code and is more powerful. The reflection types in .NET are present in a System.Reflection namespace. To work with reflection in C#, must include the System.Reflection namespace in the program.

Defining Reflection in C#

To understand reflection, there are a basics should understand about modules, types, and members:

Reflection in C#
  • Assemblies contain modules
  • Modules contain types

Need to use Reflection when wanting to inspect the contents of an assembly.

For example, you can get all members of an object by typing “.” before an object when viewing the Visual Studio editor IntelliSense. A program reflects on itself when it extracts metadata from its assemblies, then uses it to change its own behavior or inform the user Compare Reflection to C++RTTI (Runtime Type Information), except that it has a lot of capabilities. When write a C# a program that uses reflection, can use either the TypeOf operator or the GetType() method to get the object’s type.

C# Reflection

In C#reflection is a process to get metadata of the type at runtime. The System.Reflection namespace contains required classes for reflection such as:

  • Type
  • MemberInfo
  • ConstructorInfo
  • MethodInfo
  • FieldInfo
  • PropertyInfo
  • TypeInfo
  • EventInfo
  • Module
  • Assembly
  • AssemblyName
  • Pointer etc

The System.Reflection.Emit namespace contains classes to emit the metadata.

A Simple Use Case

Reflection can be used to generate applications called type browsers which allow users to select types and then read the data provided about them.

C# Type class

C# Type class denote type declarations for class types, interface types, enumeration types, array types, value types etc

  • It is find in System namespace
  • It inherits the System.Reflection.MemberInfo class.

C# Reflection Example: Get Type

  • using System;
  • public class ReflectionExample
  • {
  • public static void Main()
  • {
  • int a = 10;
  • Type type = a.GetType();
  • Console.WriteLine(type);
  • }
  • }
  • C# Reflection Example: Get Assembly
  • using System;
  • using System.Reflection;
  • public class ReflectionExample
  • {
  • public static void Main()
  • {
  • Type t = typeof(System.String);
  • Console.WriteLine(t.Assembly);
  • }
  • }

C# Reflection Example: Get Assembly

  • using System;
  • using System.Reflection;
  • public class ReflectionExample
  • {
  • public static void Main()
  • {
  • Type t = typeof(System.String);
  • Console.WriteLine(t.Assembly);
  • }
  • }

C# Reflection Example: Print Type Information

  • using System;
  • using System.Reflection;
  • public class ReflectionExample
  • {
  • public static void Main()
  • {
  • Type t = typeof(System.String);
  • Console.WriteLine(t.FullName);
  • Console.WriteLine(t.BaseType);
  • Console.WriteLine(t.IsClass);
  • Console.WriteLine(t.IsEnum);
  • Console.WriteLine(t.IsInterface);
  • }
  • }

C# Reflection Example: Print Constructors

  • using System;
  • using System.Reflection;
  • public class ReflectionExample
  • {
  • public static void Main()
  • {
  • Type t = typeof(System.String);
  • Console.WriteLine(“Constructors of {0} type…”, t);
  • ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
  • foreach (ConstructorInfo c in ci)
  • {
  • Console.WriteLine(c);
  • }
  • }
  • }

C# Reflection Example: Print Methods

  • using System;
  • using System.Reflection;
  • public class ReflectionExample
  • {
  • public static void Main()
  • {
  • Type t = typeof(System.String);
  • Console.WriteLine(“Methods of {0} type…”, t);
  • MethodInfo[] ci = t.GetMethods(BindingFlags.Public | BindingFlags.Instance);
  • foreach (MethodInfo m in ci)
  • {
  • Console.WriteLine(m);
  • }
  • }
  • }

C# Reflection Example: Print Fields

  • using System;
  • using System.Reflection;
  • public class ReflectionExample
  • {
  • public static void Main()
  • {
  • Type t = typeof(System.String);
  • Console.WriteLine(“Fields of {0} type…”, t);
  • FieldInfo[] ci = t.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
  • foreach (FieldInfo f in ci)
  • {
  • Console.WriteLine(f);
  • }
  • }
  • }

How Reflection in C# Works:

Reflection in C#

The major class for reflection is the System.Type class, which is an abstract class representing a type in the Common Type System (CTS). When using this class, can find the types used in a module and namespace and also find if a given type is a reference or value type. The corresponding metadata tables to look through these items:

  • Fields
  • Properties
  • Methods
  • Events

Late bindings can also be achieved through reflection.Might not know which arrangement to load during compile time. With the System.Reflection.Assembly type can get 3 static types which allow to load an assembly directly:

  • LoadFrom
  • LoadFrom
  • LoadWithPartialName

When considering that an assembly is a logical DLL or EXE and a manifest is an explained overview of an assembly, then it makes sense that a PE (portable executable) file for CTS has the extension of .dll or .exe. Within the PE file is mainly metadata, which contains a different tables such as a:

  • Filed definition table
  • Type definition table
  • Method definition table

When parsing these tables, it can retrieve an assembly’s types and attributes.

Uses of Reflection:

when reflections are useful in C# are:

    1. 1. Reflections are quite useful for generating new types at runtime.
    2. 2. It is simple to use reflection with the program metadata attributes.
    3. 3. Reflection is needed to examine and instantiate types in the assembly.
    4. 4. For late binding to methods and properties, reflections are useful.

Applications of Reflection:

Reflection have the following applications −

  • It allows viewing attribute data at runtime.
  • It allows examining different types in an assembly and instantiating these types.
  • It allows a late binding to methods and properties
  • It allows generating new types at runtime and then performs some tasks using those types.

Advantages:

  • Reflection increases the flexibility and scalability of the program, reduces coupling, and increases adaptive capabilities.
  • It allows programs to make and control objects of any class without having to hard-code the target class in advance

Disadvantages:

1. Performance issues:

  • The use of reflection is an interpretation operation, which is much slower than direct code when used for field and method access.
  • Therefore, the reflection mechanism is majorly used in system frameworks that need high flexibility and scalability, and it is not recommended for ordinary programs.

2. The use of reflection will obscure the internal logic of a program:

  • Programmers want to view the logic of the program in the source code, and reflection and other technologies that bypass the source code will cause maintenance problems
  • The reflection code is much more complicated than the corresponding direct code.
  • As for execution efficiency, because it is a strongly typed language with good execution efficiency.
  • It is recommended to save the reflection in the cache.
  • Although reflection is more powerful, it cannot be abused.
  • If a function can be finished without reflection, it is best not to.

The first is a performance:

  • Reflection contains some dynamic types, so the JVM cannot optimize these codes.
  • Therefore, the efficiency of reflective operations is lower than those of non-reflective operations.
  • We should avoid using reflection in frequently executed code or programs with more performance requirements.

Security:

  • The use of reflection technology needs the program to run in an environment without security restrictions.
  • If a program must run in an environment with security restrictions, like an Applet, then this is a problem.

Internal exposure of members:

  • Since reflection permits the code to perform some operations that are not allowed under normal circumstances (such as accessing private properties and methods).
  • Using reflection may cause unexpected side effects-the code has functional errors and reduces the portability.
  • Reflective code destroys abstraction, so when the platform changes, the behavior of the code may also change

Viewing Metadata:

The MemberInfo object of the System.Reflection class requires it to be initialized for discovering the attributes associated with a class. To do this, define an object of the target class, as −

System.Reflection.MemberInfo info = typeof(MyClass);

Are you looking training with Right Jobs?

Contact Us

Popular Courses