C# Reflection to Aid Us in Discovering the Metadata of Your Code

Reflection is the ability of a computer program to analyze its behavior and code and make adjustments. For example, Reflection in C# allows you to see and modify data about your program during runtime, which has enormous potential but might not see now. The reflection features in C#, sometimes known simply as "reflection," are incredibly powerful and surprisingly simple to utilize.

In this "C# Reflection" lesson, you will explore the most important technical and practical aspects of .NET Reflection libraries and metadata.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

What Is Meta Data?

Simply put, metadata is "data about data," or computerized information about a resource. Details on the format, organization, and dimensions of a data source are all examples of this kind of information. Metadata may tell the runtime, tool, or app almost all they need to know about integrating components. Metadata in .NET consists of standard information like type definitions, version numbers, and connections to external assemblies.

What Is C# Reflection?

Accessing metadata at runtime is known as a reflection in C#. Using reflection, you may dynamically access and invoke a type's methods, attributes, and events. In addition to reading and calling, reflection is used to construct new types at runtime. The "System.Reflection" namespace contains the classes that provide access to the program's metadata during runtime.

Classes in the "System.Reflection" namespace are used to learn more about an app's structure and functionality and dynamically add new data types, properties, and objects.

Classes essential for reflection are found in the System.Reflection namespace, including:

  • Assembly

An assembly is a recyclable, updatable, and self-describing component of a common language runtime program, and the Assembly class describes it.

  • AssemblyName

It Describes the assembly's nth distinguished name.

  • MemberInfo

Retrieves details about a member's properties and provides member's metadata.

  • MethodInfo

It explains the method class and provides its metadata.

  • ConstructorInfo

It explains the constructor class and provides its metadata.

  • EventInfo

It explains the event info and provides its metadata.

  • PropertyInfo

It identifies a property's features and makes its metadata available.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

C# Type Class

Class types, array types, value types, interface types, enumeration types, etc., are all represented by the Type class in C#. You may locate it in the namespace System. It is based on the "System.Reflection.MemberInfo" class.

C# Type class supports various methods:

  • GetType()

It gives the present type.

  • GetType(String)

It gives the type of given argument.

  • GetMembers()

It returns all the public members for the type.

  • GetMembers(BindingFlags)

Gets a list of all the members of the Type that match the specified requirements.

  • GetConstructors()

It returns all the public constructors for the type.

  • GetConstructors(BindingFlags)

Gets a list of all the constructors of the Type that match the specified requirements.

  • GetFields()

It returns all the public fields for the type.

  • GetFields(BindingFlags)

Gets a list of all the fields of the Type that match the specified requirements.

  • GetMethods()

It returns all the public methods for the type.

  • GetMethods(BindingFlags)

Gets a list of all the methods of the Type that match the specified requirements.

  • GetProperties()

It returns all the public properties for the type.

  • GetProperties(BindingFlags)

Gets a list of all the properties of the Type that match the specified requirements.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

Implementation of C# Reflection

Reflection-Article-Implementation-img1

We will start with creating a Console Application Project which supports the ".NET core."

Reflection-Article-Implementation-img2.

We will name this project "SimpliReflectionDemo" select the project location according to you, and hit create.

Reflection-Article-Implementation-img3.

Next, it will ask you to select the .NET version. I am using 5.0, but you can use it according to your choice. Then we will hit create.

Reflection-Article-Implementation-img4

Then we will right-click on our main project in solution explorer, select add, and choose a new project.

Reflection-Article-Implementation-img5

Then for this new project, we will choose the "Class Library," which supports C# and .NET Core, and hit next.

Reflection-Article-Implementation-img6

Let's name this project "SimplilearnPrintData" and hit create.

Reflection-Article-Implementation-img7

Then it will prompt us to specify the .NET version. You have to choose which you used earlier.

Now let's write up code for SimplilearnPrintData’s class1.cs file

Code:

using System;

namespace SimplilearnPrintData

{

    public class SimpliPrintData

    {

        private string employeeName;

        public void SimpliPrint()

        {

            Console.WriteLine("Printing from SimpliPrint");

        }

        public string SimpliGetName()

        {

            return this.employeeName;

        }

        public void SimpliPrintName()

        {

            Console.WriteLine($"Employee Name set to {this.employeeName}");

        }

        public void SimpliPrint(string employeeName)

        {

            Console.WriteLine($"Employee Name Passed as {employeeName}");

        }

        private void SimpliPrintPrivate()

        {

            Console.WriteLine("Printing from SimpliPrintPrivate");

        }

        public string EmployeeName => employeeName;

        public static String StaticEmployeeName => "Static property employeeName";

    }

}

Reflection-Article-Implementation-img8

Caltech Coding Bootcamp

Become a full stack developer in 6 monthsEnroll Now
Caltech Coding Bootcamp

Then we will rebuild the solution for the complete project and copy the path to "simpliprintdata.dll" from the build output window.

Copied Path:

C:\SimpliProject\SimplilearnPrintData\bin\Debug\net5.0\SimplilearnPrintData.dll

We will use this path in the main project's code.

Let's write up code for our main project's program file.

Code: 

using System;

using System.Linq;

using System.Reflection;

namespace SimpliReflectionDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            //paste the earlier copied path in the loadfrom field below.

            var Simpliassembly = Assembly.LoadFrom(@"C:\SimpliProject\SimplilearnPrintData\bin\Debug\net5.0\SimplilearnPrintData.dll");

            foreach (var type in Simpliassembly.GetTypes())

            {

                Console.WriteLine($"Type: {type.Name}");

                Console.WriteLine("=============================");

                var Simpliinstance = Activator.CreateInstance(type);

                foreach (var field in type.GetFields(BindingFlags.NonPublic |

                     BindingFlags.Instance |

                     BindingFlags.DeclaredOnly))

                {

                    Console.WriteLine($"Field: {field.Name}");

                    field.SetValue(Simpliinstance, "James");

                }

                Console.WriteLine("=============================");

                foreach (var method in type.GetMethods(BindingFlags.Public |

                    BindingFlags.NonPublic |

                     BindingFlags.Instance |

                     BindingFlags.DeclaredOnly)

                    .Where(m => !m.IsSpecialName))

                {

                    Console.WriteLine($"Method: {method.Name}");

                    if (method.GetParameters().Length > 0)

                    {

                        method.Invoke(Simpliinstance, new[] { "Peter" });

                    }

                    else if (method.ReturnType.Name != "Void")

                    {

                        var returnedValue = method.Invoke(Simpliinstance, null);

                        Console.WriteLine($"Returned value from method: {returnedValue}");

                    }

                    else

                    {

                        method.Invoke(Simpliinstance, null);

                    }

                }

                Console.WriteLine("=============================");

                foreach (var property in type.GetProperties())

                {

                    Console.WriteLine($"Property: {property.Name}");

                    var propertyValue = property.GetValue(Simpliinstance);

                    Console.WriteLine($"Property value: {propertyValue}");

                }

                Console.WriteLine("=============================");

            }

        }

    }

}

Article-Implementation-img9_new

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE
Full Stack Java Developer Course

Applications of C# Reflection

  • It permits the creation of new types during runtime and executes various actions utilizing those kinds.
  • Attribute information can be seen during runtime.
  • Late binding to functions and attributes is permitted.
  • It enables instantiating and inspecting numerous kinds within an assembly.
Master front-end and back-end technologies and advanced aspects in our Post Graduate Program in Full Stack Web Development. Unleash your career as an expert full stack developer. Get in touch with us NOW!

Next Steps

You can start with "Streams in C#" as your next Chapter in your path to conquering C# Programming. A stream is an organized sequence of bytes transmitted from one application or input device to another. These bytes are transmitted and read sequentially and always arrive in the same sequence as those sent.

Simplilearn is the most popular online Bootcamp in the world for learning skills for the modern economy, and it can help you do that. Our online courses detail things like digital marketing and data science.

If you want to go in-depth and learn more about software development and work in the field, you've come across the right place. The IIT-Kanpur and the Caltech CTME have worked with Simplilearn to offer their Software Development courses. These courses teach the basics of data structures and algorithms and more advanced topics such as Competitive Programming. You will learn to use data structures like trees, graphs, and queues as a software developer.

If you have questions about this "C# Reflections" lesson, feel free to post them in the comments section. Good luck with a productive educational experience!

About the Author

Vaibhav KhandelwalVaibhav Khandelwal

Vaibhav Khandelwal is a proactive tech geek who's always on the edge of learning new technologies. He is well versed in competitive programming and possesses sound knowledge of web development. He likes to read fictional and sci-fi novels and likes to play strategy games like chess

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors