Anas Ghanem
Anas Ghanem

Reputation: 127

Code analysis to tell if a given class's property is being set from inside the class

I have a class where I define some public properties (get and set). In this class, there are some functions and I need to find a way to tell if a given property is being set inside the class no matter where, just being set.

For example, Assume we have a property named P1:

Public string P1
{
    get;set;
}

Now I need to tell if this property is placed at least once in the class on the left hand side of the equality operation (value assignation).

So if there is at least a line in this class that have: P1="blah bla...", I need to get yes answer.

This is not something specific to the class instances, I need something that walk through the class code (code analysis maybe ?) and detect this for me.

I read about CodeDom that it seems it's something to build/parse a class file. What I need is to go over the code and extract this not build a file.

Upvotes: 1

Views: 234

Answers (2)

Herman Kan
Herman Kan

Reputation: 2292

If Roslyn is not an option, you can use reflection to get all constructors and methods (including getters and setters) of the target class, then call GetMethodBody().GetILAsByteArray() to get their MSIL code, and finally for each found assignment call Module.ResolveMember(token) to verify if the token represents the PropertyInfo that you are looking for.

Upvotes: 1

Dani Ribas
Dani Ribas

Reputation: 54

Try to get the current StackTrace. Then you can parse the given data.

private int t1;
public int T1
{
     get { return t1; }
     set 
     {
         t1 = value;
         Debug.WriteLine(new System.Diagnostics.StackTrace());
     }
}

Upvotes: 0

Related Questions