Invoke Method From String [using Reflection]
For Calling a function/method from a string we can use Reflection in C#.
Wikipedia says that "In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior". This is exactly how Reflection in C# works.
Uses of Reflection
Reflection has the following uses:- It allows view attribute information at runtime.
- It allows examining various types in an assembly and instantiate these types.
- It allows late binding to methods and properties
- It allows creating new types at runtime and then performs some tasks using those types.
A Sample code is given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace InvokeMethodFromString
{
class Program
{
static void Main(string[] args)
{
Type type = typeof(MyReflectionClass);
MethodInfo method = type.GetMethod("MyMethod");
MyReflectionClass c = new MyReflectionClass();
string result = (string)method.Invoke(c, new object[] { 10, 20 }); // 10 & 20 are parameter
Console.WriteLine(result);
Console.ReadKey();
}
}
public class MyReflectionClass
{
public string MyMethod(int a, int b)
{
return (a + b).ToString();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace InvokeMethodFromString
{
class Program
{
static void Main(string[] args)
{
Type type = typeof(MyReflectionClass);
MethodInfo method = type.GetMethod("MyMethod");
MyReflectionClass c = new MyReflectionClass();
string result = (string)method.Invoke(c, new object[] { 10, 20 }); // 10 & 20 are parameter
Console.WriteLine(result);
Console.ReadKey();
}
}
public class MyReflectionClass
{
public string MyMethod(int a, int b)
{
return (a + b).ToString();
}
}
}
Comments
Post a Comment