What is reflection in C#? Where do we use this concept in our applications?
Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them...
For reference, MSDN article on reflection and The Code Project has reflection pretty well explained..
For example, have a look at C# Reflection Examples.
From the documentation:
Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them. For more information, see Attributes.
Wikipedia says this:
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior. The programming paradigm driven by reflection is called reflective programming. It is a particular kind of metaprogramming.
For example, if you want to programmatically display all the methods of a class, you could do it like so:
using System;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var t = typeof(MyClass);
foreach (var m in t.GetMethods())
{
Console.WriteLine(m.Name);
}
Console.ReadLine();
}
}
public class MyClass
{
public int Add(int x, int y)
{
return x + y;
}
public int Subtract(int x, int y)
{
return x - y;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With