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.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

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.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

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.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

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

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

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

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

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.
Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer - MERN Stack Master's program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!

Next Steps

C# reflection, to put it simply, functions as a secret key to the hidden data in your code. Classes, methods, and attributes are a foundation that can be examined at runtime to increase the flexibility and adaptability of your programs. This ability can be used for a variety of purposes, such as investigating sophisticated coding approaches or quickly introducing new features. If you want to develop these dynamic apps, you might think about enrolling in classes like Full Stack Developer - MERN Stack to advance your knowledge in the field.
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, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.