inside
inside

Reputation: 3177

Find if interface is used in my project C#

I need to find if specific interface is used in project, I just found something like

Type IType = Type.GetType("iInterfaceName"); // I want to look in whole project, not in one file
if (IType == null)
{  
   Text = "Interface Not Exist";
}
else
{
    Text = "Interface Exist";
}

I am not sure if this is correct but this is the latest thing I found and in doesn't work, any help greatly appreciated...

Upvotes: 0

Views: 131

Answers (2)

e_ne
e_ne

Reputation: 8459

Assume that you have the following interface:

public interface IFoo
{
}

You can find out if there's any type implementing it this way:

var isImplemented = Assembly.GetExecutingAssembly().
                             GetTypes().
                             Any(t => t.IsAssignableFrom(typeof (IFoo)));

To use the above, add to your using directives:

using System.Linq;

For .NET 2.0:

var isImplemented = false;
foreach (var t in Assembly.GetExecutingAssembly().GetTypes())
{
    if (!t.IsAssignableFrom(typeof (IFoo))) continue;
    isImplemented = true;
    break;
}
//Operate

Upvotes: 1

Corey Adler
Corey Adler

Reputation: 16137

Use Assembly.Load before you go for GetType as follows:

Assembly.Load("YourProjectName")
        .GetType("iInterfaceName");

Upvotes: 1

Related Questions