Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is reflection in C#? Where do we use this concept in our application? [closed]

Tags:

c#

asp.net

What is reflection in C#? Where do we use this concept in our applications?

like image 839
HITESH Avatar asked Apr 26 '10 10:04

HITESH


2 Answers

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.

like image 109
ACP Avatar answered Sep 30 '22 15:09

ACP


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;
        }
    }
}
like image 37
Klaus Byskov Pedersen Avatar answered Sep 30 '22 14:09

Klaus Byskov Pedersen