0

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...

inside
  • 3,047
  • 10
  • 49
  • 75
  • 2
    Related http://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface-with-c-sharp-3-5 and http://stackoverflow.com/questions/927861/how-to-find-what-classes-implements-an-interface-net – Soner Gönül Jan 09 '13 at 21:23
  • oops, didn't see it... so sorry – inside Jan 09 '13 at 21:25

2 Answers2

1

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

Assembly.Load("YourProjectName")
        .GetType("iInterfaceName");
Corey Adler
  • 15,897
  • 18
  • 66
  • 80
1

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
e_ne
  • 8,340
  • 32
  • 43
  • I am using .net 2.0, don't have System.linq – inside Jan 09 '13 at 21:34
  • it gives me IFoo(where iFoo is my interface name) can not be found error – inside Jan 09 '13 at 21:43
  • and it makes sense because I don't know if this interface is used in my application, I need to find it on runtime – inside Jan 09 '13 at 21:45
  • @Stanislav You need to post more information about your error. Compile time, run-time? Update your post. – e_ne Jan 09 '13 at 21:46
  • sorry, Error 1 The type or namespace name 'IFoo' could not be found (are you missing a using directive or an assembly reference?) – inside Jan 09 '13 at 21:47
  • @Stanislav C# is case-sensitive. `iFoo` and `IFoo` are not the same. – e_ne Jan 09 '13 at 21:48
  • alright fixed that but now if statement gives an error: Error SA1503: The body of the if statement must be wrapped in opening and closing curly brackets. – inside Jan 09 '13 at 22:05
  • @Stanislav Sorry but I can't help you with that. You have a perfectly working piece of code and you can adapt it to your needs. Please try to do that. Probably you erased a closing curly bracket and you need to put it back. – e_ne Jan 09 '13 at 22:16
  • thanks for help, I don't see any problem with this if statement either, but it gives me an error for no reason... – inside Jan 09 '13 at 22:22