0

In VB.NET or C#, is there a way to determine if a class has been extended with extension methods?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Rabskatran
  • 2,269
  • 5
  • 27
  • 41

3 Answers3

7

EDIT: Now the question has been changed to refer to extension methods (which may or may not be the OP's intention) - no, you can't tell whether a type is the target of extension methods unless it's a static class (in which case it can't be used that way), unless you know all the relevant potential assemblies.

An extension method is just a static method in a static non-generic top-level type, decorated with an attribute. You're effectively asking whether such a method exists. You could iterate over all the methods in all the assemblies you care about to try to find an extension method targeting that type, but that's all.


Original answer, when the question didn't mention extension methods

If you know all the assemblies in which it might be extended, you could check each of them using Assembly.GetTypes and Type.IsSubclassOf.

If the class is unsealed and contains no internal abstract members (i.e. it can be extended), then you can't tell whether some other, unloaded assembly contains a subclass, no. Each class "knows" about its parent, but not its children.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

If a class is protected, or public, practically there is no way to determine if it is extended or not.

If you want to determine within assembly, or within process (all loaded assemblies), you can check using Type.IsSubclassOf, or Type.IsAssignableForm.

If you want to determine at compile time (without actually executing) within the solution, just make the constructor private, or mark the class as sealed, compile the solution, and check all the related errors. Once done, revert the changes.

Tilak
  • 30,108
  • 19
  • 83
  • 131
1

It is not possible to know whether a class has been extended with extension methods. Think of extension methods as static procedures that are attached to the class only weakly and differently in different projects.

Extension methods do not create any new types and can never override genuine member methods (so they cannot change the behavior of an object in any way until you start directly calling them). It is therefore possible that you do not need to detect their existence.

It is possible to determine whether a particular method is an extension method, or a genuine member method. It is also possible to list all extension methods in a specific loaded assembly using reflection. This is explained here.

Community
  • 1
  • 1
Jirka Hanika
  • 13,301
  • 3
  • 46
  • 75