views:

582

answers:

1

I have a problem with reflection. I need to find the type that instantiates a static member. My code looks like this:

    private class SimpleTemplate : PageTemplate
    {
        internal static readonly IPageProperty NameProperty =
            PropertyRepository.Register("Name");
    }

The PropertyRepository is a repository of properties (obviously). It keeps track of all the properties that have been registered using the type system that I'm building.

In order to do that successfully, I need to keep track of all the properties but also the type on which they are defined. Otherwise, if two properties with the same name are defined, the property repository won't be able to tell them apart.

So, what I want to do is to find out the type that defines the NameProperty and store the type as well as the name. How can I do that?

I want to use strong typing, i.e. I do not want to send the type as an argument to PropertyRepository.Register. That would be error-prone since I can't validate that the type argument is correct.

The solution, I imagine, would involve reflection. Is there any way to use reflection to determine which type calls a static method? The static properties are implicitly instantiated using a static constructor (that the compiler generates). Is there a way for me to get a handle to that constructor? That seems feasible, I just cannot figure out how to do that.

In other words: If method A calls method B, is there any way B can tell that it was called from A using reflection? I imagine there is, but I cannot find out how.

Does anyone know?

Edit: I've looked at the StackFrame class and while it seems to do what I want, it may not be reliable in production code (and I need that).

+1  A: 

This is almost a duplicate of this question, but not quite. Look at that one's answers though.

Personally I think I'd pass in the type. An alternative would be to use an attribute, e.g.

[PropertyName("Name")]
private static readonly IPageProperty NameProperty = null;

static
{
    PropertyRepository.RegisterProperties(typeof(SimpleTemplate));
}

PropertyRepostiory.RegisterProperties could then set the value of the readonly field using reflection (if this works - I haven't tried it; the readonly-ness might be enforced). It's a bit icky though... Alternatively, you could just get the property from the repository when you need it.

Jon Skeet
Yes, the link you point to clearly helps. And your comment make me realize that there is a simpler way to do this, even though it won't be exactly what you suggest. Thanks!
Karl