What is Reflection in C#? | Learn Now Tutorial
Reflection in C Tutorial ACTE

What is Reflection in C#? | Learn Now Tutorial

Last updated on 01st Feb 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) | 18751 Ratings 1956
    • Introduction to Reflection in C#
    • Uses of Reflection
    • Seeing Metadata<
    • Uses of Reflection
    • Advantages of utilizing reflection
    • Show metadata
    • About Reflection in C#
    • Reflection namespace
    • Historical background
    • Uses of Reflection in C#
    • Reflection is likewise a key approach for metaprogramming
    • Conclusion

    Subscribe For Free Demo


      Introduction to Reflection in C#

      Reflection items are used for acquiring kind facts at runtime. Allows overdue binding to strategies and properties. You can create new kinds at run time and use them to carry out a few tasks. The classes that give admittance to the metadata of a running project are in the System. Reflection namespace. The System. The reflection namespace contains classes that permit you to get data about the application and powerfully add types, qualities, and objects to the application.

      Uses of Reflection

      Reflection has the accompanying applications −

    • It permits view characteristic data at runtime.
    • It permits analyzing different sorts in a gathering and launching these sorts.
    • It permits late restricting to techniques and properties
    • It permits making new sorts at runtime and afterward playing out certain undertakings utilizing those types.

    • Seeing Metadata

      We have referenced in the previous section that utilizing reflection you can see the property data. The MemberInfo object of the System. Reflection class should be introduced for finding the characteristics related with a class. To do this, you characterize an object of the objective class, as −

      • System.Reflection.MemberInfo information = typeof(MyClass);

      Uses of Reflection

      A portion of the circumstances when reflections are valuable in C# are given as follows:

    • Reflections are very valuable for making new sorts at runtime.
    • It is not difficult to utilize reflection with the program metadata ascribes.
    • Reflection is expected to look at and starting up types in a gathering.
    • For late restricting to strategies and properties, reflections are very valuable.

    • System.Reflection Namespace

      The System. The reflection namespace is expected to involve reflections as it has classes that permit the client to get the data expected with regards to an application. It additionally permits the client to powerfully add objects, types, values, and so forth to the application.

      TypeInfo Class

      The TypeInfo class is one of the classes in the System. Reflection namespace. It addresses type revelations for class types, cluster types, interface types, esteem types, list types, and so forth This class acquires the IReflectable Type interface.

      Advantages of utilizing reflection

    • To peruse gathering metadata.
    • To conjure get together reference on a runtime.
    • In the event that you are fostering IDE resembles visual studios, to show individuals from a class you can utilize Reflection.
    • You can utilize reflection anyplace, where you need to powerfully show all individuals from DLL.
    • So hello companions this is about the appearance in C#. In the event that you have more questions or inquiries kindly go ahead and drop your remark in the underneath remark area.
    • In the event that you like this article, share it with your companions on Google+, Facebook, and Twitter.

    • Course Curriculum

      Learn Advanced C# Certification Training Course to Build Your Skills

      Weekday / Weekend BatchesSee Batch Details

      Show metadata

      In the preceding chapter, we defined that you may use a mirrored image to show characteristic facts.

      The MemberInfo item of the System. Reflection elegance desires to be initialized to decide the attributes related to the elegance. To do this, outline an item of the goal elegance as follows: –

      • System.Reflection.MemberInfoinfo = typeof (MyClass);

      About Reflection in C#

    • The ability to find out information about objects at runtime is called Reflection. In The reflection we can find out the object`s class, details of an object`s methods, and even create one dynamically at runtime. Reflection is a powerful mechanism with the
      System. Reflection namespace contains nearly forty classes and interfaces.
    • The Type class is the root of all reflection operations and the Object that represents a type inside the system. Type is an abstract base class that allows multiple implementations.

    • This class is the primary means of accessing metadata and acts as a gateway to the Reflection API. This Provides methods for retrieving information about type declarations, such as: B. Constructor, method, field, Class properties and events, and modules and assemblies in which the class is deployed.

    • A very useful feature related to reflection is the ability to dynamically create objects and call methods on them. she You can specify the required class as a Type object, or you can specify the assembly name

    • and class as a string.

      You can get the name of the class from the user and create an object of the appropriate type. You can then manipulate as if you were creating a new object from scratch, and use reflection to see what you’re doing with the:

      Sample Example

      • using System;
      • using System.Reflection;
      • namespace ConsoleReflection
      • {
      • class Program
      • {
      • static void Main(string[] args)
      • {
      • string _name;
      • }
      • }
      • }

      Reflection namespace

      To use .NET reflection, you need to include two main namespaces.


      The system provides the Type class. Type classes represent class types, interface types, array types, value types, enums, type parameters, generic type definitions, and open / closed generic types. Type provides very useful properties and methods for getting information about the type.

    • assembly
    • Is Abstract
    • isArray
    • IsClass
    • IsGenericParameter
    • IsGenericTypeDefinition
    • IsInterface
    • Nested
    • IsPublic
    • Not published
    • IsValueType
    • ?? GetConstructors
    • GetInterface
    • GetMembers
    • GetMethods
    • GetProperties

    • System.Reflection contains important classes for retrieving types and their information in an assembly. The important classes are:

    • Assembly
    • ConstructorInfo
    • EventInfo
    • FieldInfo
    • MemberInfo
    • MethodInfo
    • ParameterInfo
    • PropertyInfo
    • TypeInfo
    • C # Described all namespaces required to use reflection. The next few sessions will show you how to use the above classes and some examples.

    • Historical background

      The earliest computer systems have been programmed of their local meeting languages, which have been inherently reflective[citation needed], as those authentic architectures may be programmed with the aid of using defining commands as statistics and the usage of self-enhancing code. As the majority of programming moved to higher-stage compiled languages which include Algol, Cobol, Fortran, Pascal, and C, this reflective cappotential in large part disappeared till new programming languages with mirrored image constructed into their kind structures appeared. Brian Cantwell Smith`s 1982 doctoral dissertation delivered the perception of computational mirrored image in procedural programming languages and the perception of the meta-round interpreter as a aspect of 3-Lisp.

      Uses of Reflection in C#

    • Reflection enables programmers make usual software program libraries to show statistics, procedure extraordinary codecs of statistics, carry out serialization or deserialization of statistics for communication, or do bundling and unbundling of statistics for packing containers or bursts of communication.

    • Effective use of mirrored image nearly usually calls for a plan: A layout framework, encoding description, item library, a map of a database or entity relations.

    • Reflection makes a language greater proper to network-orientated code. For example, it assists languages which include Java to function nicely in networks with the aid of using allowing libraries for serialization, bundling and ranging statistics codecs.

    • Languages with out mirrored image which include C are required to apply auxiliary compilers for obligations like Abstract Syntax Notation to provide code for serialization and bundling.

    • Reflection may be used for staring at and enhancing software execution at runtime. A mirrored image-orientated software aspect can display the execution of an enclosure of code and may adjust itself in keeping with a favored intention of that enclosure. This is normally completed with the aid of using dynamically assigning software code at runtime.

    • In item-orientated programming languages which include Java, mirrored image lets in inspection of lessons, interfaces, fields and strategies at runtime with out understanding the names of the interfaces, fields, strategies at bring together time. It additionally lets in instantiation of latest items and invocation of strategies.

    • Reflection is regularly used as a part of software program testing, which include for the runtime creation/instantiation of mock items.

    • Reflection is likewise a key approach for metaprogramming

      In a few item-orientated programming languages which include C# and Java, mirrored image may be used to pass member accessibility rules. For C#-homes this will be done with the aid of using writing without delay onto the (typically invisible) backing area of a private property. It is likewise viable to locate private strategies of lessons and brands and manually invoke them. This works for project-inner documents in addition to outside libraries which include .NET’s assemblies and Java’s archives.


      A language helping mirrored image offers some of the functions to be had at runtime that might in any other case be hard to perform in a lower-stage language. Some of those functions are the competencies to:

    • Discover and regulate supply-code constructions (inclusive of code blocks, classes, strategies, protocols, etc.) as great gadgets at runtime.
    • Convert a string matching the symbolic call of a category or feature right into a connection with or invocation of that magnificence or feature.
    • Evaluate a string as though it had been a supply-code announcement at runtime.
    • Create a brand new interpreter for the language`s bytecode to provide a brand new that means or motive for programming construct.

    • These functions may be carried out in one-of-a-kind ways. In MOO, mirrored image bureaucracy a herbal a part of a normal programming idiom. When verbs (strategies) are called, numerous variables inclusive of the verb (the call of the verb being called) and this (the item on which the verb is called) are populated to provide the context of the call. Security is normally controlled via way of means of getting access to the caller stack programmatically:

      Course Curriculum

      Get JOB Oriented C# Training for Beginners By MNC Experts

      • Instructor-led Sessions
      • Real-life Case Studies
      • Assignments
      Explore Curriculum

    • Since callers() is a listing of the strategies via way of means of which the modern-day verb changed into subsequently called, acting assessments on callers()[0] (the command invoked via way of means of the authentic user) permits the verb to shield itself in opposition to unauthorized use.

    • Compiled languages rely upon their runtime machine to offer facts approximately the supply code. A compiled Objective-C executable, for example, facts the names of all strategies in a block of the executable, supplying a desk to correspond those with the underlying strategies (or selectors for those strategies) compiled into the application.

    • In a compiled language that helps runtime introduction of functions, inclusive of Common Lisp, the runtime surroundings should consist of a compiler or an interpreter.

    • Reflection may be carried out for languages without integrated mirrored image via way of means of the usage of an application transformation machine to outline computerized supply-code changes.

    • C # reflection

      In C #, reflection is the process of getting certain types of metadata at run time. The System. The reflection namespace contains the classes needed for reflection. Example:

    • type
    • Member information
    • Constructor information
    • Method information
    • Field information
    • Property information
    • TypeInfo
    • event information
    • module
    • assembly
    • AssemblyName
    • The System.Reflection.Emit namespace contains classes for publishing metadata.

    • C # typeclass

      A-C # type class represents a type declaration such as a class type, an interface type, an enumeration type, an array type, or a value type. It resides in the System namespace. Inherit the System.Reflection.MemberInfo class.

      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);
      • }
      • }
      • }


    • Fields of System.String type
    • System.String Empty
    • Int32 TrimHead
    • Int32 TrimTail
    • Int32 TrimBoth
    • Int32 charPtrAlignConst
    • Int32 alignConst

    • C and C Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download


      Reflection gives objects (of Type) that depict congregations, modules, and types. You can utilize reflection to progressively make an occasion of a kind, tie the sort to a current article, or get the sort from a current item and summon its strategies or access its fields and properties. Reflection gives us data about the class to which an item has a place and furthermore the techniques for that class that can be executed by utilizing the article. Through reflection, we can summon strategies at runtime independent of the entrance specifier utilized with them.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free