I need some solution to trace the class-owner of a method, in which the object is constructed. I mean to say, I want the constructor to automatically resolve the Type object of the “creator” class. Is it possible in C#?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Assuming that inlining of the method that needs to check its caller and permissions aren’t a problem, you can call the following method in a constructor:
So for your real question, the answer is yes, it is possible, but not recommended.
EDIT:
The method will require the reflection permission to access the
GetMethod()method and theDeclaringTypeproperty. For the stack trace, a security permission for unmanaged code is needed (if I understand the documentation correctly), which basically renders this method useless for anything less than fully trusted code.As you see, I decorated the method with an attribute that explicitly requests the JIT not to inline the method, since it walks at least one frame up the call stack. Problems arise if the calling method becomes inlined (or whatever transform the JIT applies) in its own calling method. I can give a sample with a short property, since properties are likely to be inlined by the JIT, though I cannot guarantee that this is corret:
While this is pretty exotic (the property is not a ‘property of an object’, it is a factory), this has at least one problem: