Invoke Method using Reflection in C#

What is Reflection?

Reflection allow you to read its own metadata for the purpose of finding assemblies, modules and type information at runtime.The classes that give access to the metadata of a running program are in the System.Reflection namespace.
The below example demonstrate for invoking methods using Reflection in C#
class Program
{
public class Person
{
public string Name { get; set; }
public string Speak()
{
return string.Format("Hello:{0}", Name);
}
}
static void Main(string[] args)
{
var jameel = new Person {Name = "Jameel"};
Type type = jameel.GetType();
//Calling the method Speak using Reflection
object result = type.GetMethod("Speak").Invoke(jameel, null);
Console.WriteLine(result);
Console.ReadLine();
}
}

Enjoy coding…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s