Skip to content

Instantly share code, notes, and snippets.

@mrnkr
Created June 10, 2019 17:29
Show Gist options
  • Save mrnkr/55171a10a31456f6b074105aa33dc111 to your computer and use it in GitHub Desktop.
Save mrnkr/55171a10a31456f6b074105aa33dc111 to your computer and use it in GitHub Desktop.
A simple example of reflection. Getting the first class that implements a given interface and calling one of its methods.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using FindMe;
namespace TestProj
{
class Program
{
static void Main(string[] args)
{
Assembly assem2 = Assembly.Load("FindMe");
Type[] types = assem2.GetTypes();
Type targetIface = typeof(IOperator);
var implQuery =
from type in types
where (targetIface.IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface)
select type;
Type myType = implQuery.FirstOrDefault();
IOperator instance = (IOperator)Activator.CreateInstance(myType);
instance.Operate();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment