Question

What is the property of the C# language that makes reflection possible? Is it something that all object oriented language can do or is it something that all interpreted language can do? Or something else...

Was it helpful?

Solution

A compiler knows a lot about the program you write. It knows every class you programmed, the names of the methods, the arguments they take. Traditionally, compilers threw that extra info about your program away after they generated the executable code for your program.

Not a .NET compiler, it preserves that info. It is stored in the metadata of an assembly. An extra data structure in a .NET .exe or .dll file, beyond the generated code. With plumbing in the runtime support library to read that data structure at runtime, the System.Type class is instrumental.

That's not where it ends, you can also add arbitrary extra data to that metadata. Which is what an [attribute] is all about.

This enables all kinds of very interesting and useful features. Like dynamically altering the way code gets generated at runtime. Or dynamically creating objects without knowing their class names. Or converting the view of a type from its implementation to a useful other representation that's easier to handle. Which in turn enables features like serialization and design-time support. Reflection is the engine behind this, metadata is the source.

OTHER TIPS

Metadata of all types/methods in C# can be accessed by reflection. Usually you have to use BindingFlags to specify types of objects you need.

Example:

MethodInfo[] myArrayMethodInfo1 = myType.GetMethods(BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.DeclaredOnly);

Reflection is the ability for a language to be his own meta language.

For example:

int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

You can apply it to classes, objects and methods.

C# is a compiled language and the byte-code generated by the C# compiler is interpreted by the virtual machine. reflection is not tied to a specific paradigm it depends on how the language is designed.

In a summary to what Hans Passant says,

every compiled C# program is encoded into a relational database—this is called metadata. With reflection we act upon the data in this special database.

what is reflection in C#, what are the benefit. How to use it to get benifit

read this too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top