Create Entity Class
Create Entities folder and create new class named Student.cs as below:
namespace LearnAdvancedCSharpWithRealApps.Entities
{
public class Student
{
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Hello()
{
return "Hello " + Name;
}
public string Hi(string Message)
{
return "Hi " + Message;
}
public double Avg(double Math, double Physical, double Chemistry)
{
return (Math * 3 + Physical * 2 + Chemistry) / 6;
}
}
}
Run Application
using LearnAdvancedCSharpWithRealApps.Entities;
using System;
using System.Reflection;
namespace LearnAdvancedCSharpWithRealApps
{
class Program
{
static void Main(string[] args)
{
var student = new Student {
Id = "st01",
Name = "Name 1",
Age = 20
};
InvokeHelloMethod(student);
InvokeHiMethod(student);
InvokeAvgMethod(student);
Console.ReadLine();
}
private static void InvokeHelloMethod(object obj)
{
Type type = obj.GetType();
MethodInfo methodInfo = type.GetMethod("Hello", new Type[] { });
string result = methodInfo.Invoke(obj, new object[] { }).ToString();
Console.WriteLine(result);
}
private static void InvokeHiMethod(object obj)
{
Type type = obj.GetType();
MethodInfo methodInfo = type.GetMethod("Hi", new Type[] { typeof(string) });
string result = methodInfo.Invoke(obj, new object[] { "Name 2" }).ToString();
Console.WriteLine(result);
}
private static void InvokeAvgMethod(object obj)
{
Type type = obj.GetType();
MethodInfo methodInfo = type.GetMethod("Avg", new Type[] { typeof(double), typeof(double), typeof(double) });
string result = methodInfo.Invoke(obj, new object[] { 6.5, 9.5, 10 }).ToString();
Console.WriteLine(result);
}
}
}
Output
Hello Name 1
Hi Name 2
8.08333333333333