How to get all types that implement a specific Interface in C# and VB.NET

To retrieve a IEnuemerable of all types in the current or another Assembly that implement a specific Interface / Abstract class and so on, you can use the snippets below.

Methods

C# Version

VB.NET Version

Compatibility: working .NET 2.0 working .NET 3.0 not tested .NET 3.5 not working .NET 4.0 not working .NET 4.5

Do you have an alternate or better method for this task?
If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

Please rate this snippet

How to get return Value from method invocation using reflection in C# and VB.NET

To get return Value from method invocation using reflection in C# and VB.NET you can use the snippet below.

Sample C#

var returnValue = (Int32)methodInfo.Invoke(null,null); //just cast the returned object of Invoke to the needed Type. Theres no difference if it is a static method/class or not

Sample VB.NET

Dim returnValue = DirectCast(methodInfo.Invoke(Nothing, Nothing), Int32) 'just cast the returned object of Invoke to the needed Type. Theres no difference if it is a static method/class or not

For more informations on how to invoke methods from other assemblies using reflection see:

  • How to call a static method in different assembly using Reflection in C# and VB.NET
  • How to call a non-static method in different assembly using Reflection in C# and VB.NET
  • Please rate this snippet

    How to call a non-static method in different assembly using Reflection in C# and VB.NET

    To call a static method in different assembly using Reflection in C# and VB.NET you can use the snippet below.

    Sample C#

    Assembly assembly = Assembly.LoadFile(@"Assembly_Location");   
    var type = assembly.Types().FirstOrDefault(x => x.FullName.Contains("MyClassName"));
    var constructor = type.GetConstructor(Type.EmptyTypes);
    
    var classObject = constructor.Invoke(new object[] { }); //call parameterless constructor
    var classObject = constructor.Invoke(new object[] { param1 }); //call non-parameterless constructor
    
    MethodInfo methodInfo = type.GetMethod("MyMethodName");
    methodInfo.Invoke(classObject, new object[] { }); //pass classobject, parameterless method
    methodInfo.Invoke(classObject, new object[] { param1 }); //pass classobject, parameterized method
    

    Sample VB.NET

    Dim assembly__1 As Assembly = Assembly.LoadFile("Assembly_Location")
    Dim type__2 = assembly__1.Types().FirstOrDefault(Function(x) x.FullName.Contains("MyClassName"))
    Dim constructor = type__2.GetConstructor(Type.EmptyTypes)
    
    Dim classObject = constructor.Invoke(New Object() {})'call parameterless constructor
    Dim classObject = constructor.Invoke(New Object() {param1})'call non-parameterless constructor
    
    Dim methodInfo As MethodInfo = type__2.GetMethod("MyMethodName")
    methodInfo.Invoke(classObject, New Object() {})'pass classobject, parameterless method
    methodInfo.Invoke(classObject, New Object() {param1})'pass classobject, parameterized method
    

    Please rate this snippet

    How to call a static method in different assembly using Reflection in C# and VB.NET

    To call a static method in different assembly using Reflection in C# and VB.NET you can use the snippet below.

    Sample C#

    Assembly assembly = Assembly.LoadFile(@"Assembly_Location"); 
    var t = assembly.Types().FirstOrDefault(x=>x.FullName.Contains("MyClassName"));
    var method = t.GetMethod("MyMethodName", BindingFlags.Public | BindingFlags.Static);
    method.Invoke(null, null); //assuming that the method does not have parameters
    method.Invoke(null, new object[] { param1}); //assuming that the method has 1 parameter
    

    Sample VB.NET

    Dim assembly__1 As Assembly = Assembly.LoadFile("Assembly_Location")
    Dim t = assembly.Types().FirstOrDefault(Function(x) x.FullName.Contains("MyClassName"))
    Dim method = t.GetMethod("MyMethodName", BindingFlags.[Public] Or BindingFlags.[Static])
    method.Invoke(Nothing, Nothing) 'assuming that the method does not have parameters
    method.Invoke(Nothing, New Object() {param1}) 'assuming that the method has 1 parameter
    

    Please rate this snippet

    Dynamic Event Subscription using C# or VB.NET

    The following snippet let you dynamically subscribe to events using C# or VB.NET.

    Sample C#

    //usage DynamicEventSubscription("button1", "Click", "button1_Click");
    public void DynamicEventSubscription(string controlName,string eventName, string targetName, bool recursiveSearch=false)
    {
    	if (controlName == String.Empty) { throw new ArgumentNullException("controlName"); }
    	if (eventName == String.Empty) { throw new ArgumentNullException("eventName"); }
    	if (targetName == String.Empty) { throw new ArgumentNullException("targetName"); }
    
    	try
    	{
    		var eventMethod = GetType().GetMethod(targetName);
    		var control = Controls.Find(controlName, false).FirstOrDefault();
    		if (control != null)
    		{
    			var eventToSubscribe = control.GetType().GetEvent(eventName);
    			var handler = Delegate.CreateDelegate(eventToSubscribe.EventHandlerType, this, eventMethod);
    			var button = Controls.Find(controlName, recursiveSearch).FirstOrDefault();
    			eventToSubscribe.AddEventHandler(button, handler);
    		}
    	}
    	catch (Exception ex)
    	{
    		//handle the exception your way
    	}
    }
    

    Sample VB.NET

    'usage DynamicEventSubscription("button1", "Click", "button1_Click")
    Public Sub DynamicEventSubscription(controlName As String, eventName As String, targetName As String, Optional recursiveSearch As Boolean = False)
    	If controlName = [String].Empty Then
    		Throw New ArgumentNullException("controlName")
    	End If
    	If eventName = [String].Empty Then
    		Throw New ArgumentNullException("eventName")
    	End If
    	If targetName = [String].Empty Then
    		Throw New ArgumentNullException("targetName")
    	End If
    
    	Try
    		Dim eventMethod = [GetType]().GetMethod(targetName)
    		Dim control = Controls.Find(controlName, False).FirstOrDefault()
    		If control IsNot Nothing Then
    			Dim eventToSubscribe = control.[GetType]().GetEvent(eventName)
    			Dim handler = [Delegate].CreateDelegate(eventToSubscribe.EventHandlerType, Me, eventMethod)
    			Dim button = Controls.Find(controlName, recursiveSearch).FirstOrDefault()
    			eventToSubscribe.AddEventHandler(button, handler)
    		End If
    			'handle the exception your way
    	Catch ex As Exception
    	End Try
    End Sub
    

    In order to make this snippet work, you need to ensure that the target method is accessible via reflection. If you use .net 3.5 or lower, remove the optional parameter from the method signature.

    Was this snippet helpful? Do you know a better way to do this? Feel free to post a comment!

    Please rate this snippet

    How to get the name of the calling method in C# and VB.NET

    To get the name of the calling method in C# and VB.NET you can use the snippet below.

    Sample C#

    public static string GetCallingMethodName()
    {
    	var stackTrace = new StackTrace();
    	return stackTrace.GetFrame(1).GetMethod().Name;
    }
    

    Sample VB.NET

    Public Shared Function GetCallingMethodName() As String
    	Dim stackTrace = New StackTrace()
    	Return stackTrace.GetFrame(1).GetMethod().Name
    End Function
    

    Please rate this snippet

    Assembly version info extension methods for C# and VB.NET

    This snippet will give you Assembly version info extension methods for C# and VB.NET.

    Sample C#

    public static string GetVersion(this Assembly assembly)
    {
    	if (assembly == null)
    	{
    		throw new ArgumentNullException();
    	}
    	var assemblyName = assembly.GetName();
    	var version = assemblyName.Version;
    	return version.ToString();
    }
    
    public static string GetMajor(this Assembly assembly)
    {
    	if (assembly == null)
    	{
    		throw new ArgumentNullException();
    	}
    	var assemblyName = assembly.GetName();
    	var version = assemblyName.Version;
    	return version.Major.ToString();
    }
    
    public static string GetMinor(this Assembly assembly)
    {
    	if (assembly == null)
    	{
    		throw new ArgumentNullException();
    	}
    	var assemblyName = assembly.GetName();
    	var version = assemblyName.Version;
    	return version.Minor.ToString();
    }
    
    public static string GetBuild(this Assembly assembly)
    {
    	if (assembly == null)
    	{
    		throw new ArgumentNullException();
    	}
    	var assemblyName = assembly.GetName();
    	var version = assemblyName.Version;
    	return version.Build.ToString();
    }
    
    public static string GetRevision(this Assembly assembly)
    {
    	if (assembly == null)
    	{
    		throw new ArgumentNullException();
    	}
    	var assemblyName = assembly.GetName();
    	var version = assemblyName.Version;
    	return version.Revision.ToString();
    }
    

    Sample VB.NET

    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function GetVersion(assembly As Assembly) As String
    	If assembly Is Nothing Then
    		Throw New ArgumentNullException()
    	End If
    	Dim assemblyName = assembly.GetName()
    	Dim version = assemblyName.Version
    	Return version.ToString()
    End Function
    
    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function GetMajor(assembly As Assembly) As String
    	If assembly Is Nothing Then
    		Throw New ArgumentNullException()
    	End If
    	Dim assemblyName = assembly.GetName()
    	Dim version = assemblyName.Version
    	Return version.Major.ToString()
    End Function
    
    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function GetMinor(assembly As Assembly) As String
    	If assembly Is Nothing Then
    		Throw New ArgumentNullException()
    	End If
    	Dim assemblyName = assembly.GetName()
    	Dim version = assemblyName.Version
    	Return version.Minor.ToString()
    End Function
    
    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function GetBuild(assembly As Assembly) As String
    	If assembly Is Nothing Then
    		Throw New ArgumentNullException()
    	End If
    	Dim assemblyName = assembly.GetName()
    	Dim version = assemblyName.Version
    	Return version.Build.ToString()
    End Function
    
    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function GetRevision(assembly As Assembly) As String
    	If assembly Is Nothing Then
    		Throw New ArgumentNullException()
    	End If
    	Dim assemblyName = assembly.GetName()
    	Dim version = assemblyName.Version
    	Return version.Revision.ToString()
    End Function
    

    Please rate this snippet

    How to get the Calling Assembly in C# or VB.NET

    To get the Calling Assembly in C# or VB.NET you can use Reflection.

    Sample C#

    using System.Reflection;
    
    public static string GetCallingAssemblyName()
    {
    var callingAssembly = Assembly.GetCallingAssembly();
    return callingAssembly.FullName;
    }
    

    Sample VB.NET

    Imports System.Reflection
    
    Public Shared Function GetCallingAssemblyName() As String
        Dim callingAssembly = Assembly.GetCallingAssembly()
        Return callingAssembly.FullName
    End Function
    

    for more informations see the MSDN: Reflection (C# and Visual Basic), Assembly.GetCallingAssembly Method

    Please rate this snippet