Offler
Offler

Reputation: 1223

Find all static references to a class by code c#

I search for a way to display all static occurances of classes (similiar to the Visual Studio functionality: find all references).

It should only be by code and not manually.

I want to

  1. Only list classes with a specific attribute
  2. List all classes which have static references to it (find table bindings to data classes)

My first step is to list all Types which i'm interested in:

            var result = from t in assembly.GetTypes()
                         where t.IsDefined(typeof(TAttribute), inherit)
                         select t;

            return result.ToList();

I'm having problems with the second step. I know how to find Properties... from a class. But how is it possible to go the other way round, and find all usages of a class?

Upvotes: 0

Views: 454

Answers (2)

Nir
Nir

Reputation: 29594

You can't find references in method bodies using reflection but you can find fields, properties and methods parameters/return values.

You already know how to list all types, now for each type:

Type.GetProperties returns an array of PropertyInfo, you can check if `PropertyInfo.ProeprtType' is in the list of types you care about.

Same goes for fields with Type.GetFields

For methods you call Type.GetMethods, this returns an array of MethodInfo objects, to get the return type you check MethodInfo.ReturnType and for the parameters call MethodInfo.GetParameters and ParameterInfo.ParameterType

That's only leaves local variables defined inside method bodies and those cannot be accessed with reflections

Upvotes: 1

Tigran
Tigran

Reputation: 62246

You can not find static references using reflection, it's something that AST may know about. For this you may want to use: Roslyn (Compiler as a Service), that let's you compile, and investigate AST.

Upvotes: 3

Related Questions