tags:

views:

33

answers:

2

Say I have a base class in Assembly A:

public class MyBaseClass{
    public static Assembly GetMyAssembly(){
     //determine the Assembly of my subclasses
    }
}

Then I create a subclass of that class within Assembly B:

public class MySubClass : MyBaseClass {
}

From there, in my domain specific logic I invoke MySubClass.GetMyAssembly(). This logic may be in the same assembly as MySubClass OR it could be in a separate assembly. How can I determine the assembly containing the subclass that invoking the inherited method? (without overriding it) I have tried to use the different Assembly.Get*() methods in System.Reflection without any luck.

A: 

I'd recommend, rather than using the Assembly.Get*() methods, you take a look at the Type object itself - it has some very useful properties and methods:

this.GetType().BaseType.Assembly;

If you're looking to simply get the assembly of a specific base class, you'll need to use typeof(MyBaseClass).Assembly - since your class should be aware of its inheritance chain, I don't think it will be an issue.

mattdekrey
I await some clarification from the OP, but it sounds like he wants the opposite solution. To get all the subclasses from within the context of the base class. If that's the case, he'll have no choice but to use AppDomain.CurrentDomain.GetAssemblies().
Kirk Woll
Oh, good point. I guess I may not have been fully awake when I read the question. I do wish, however, there was something like a typeof(self) for use with static methods... especially for static methods on inheritable classes. That may be what wintondeshong is looking for.
mattdekrey
A: 

You can't. This static method really does live in the assembly that has the base type.

The best you could do is use an instance method (omit the static keyword) so the code has access to the this reference. The this.GetType() expression gives you the derived type. Its Assembly property gives you the assembly that contains the derived type.

Hans Passant
Thank you for your answer as well as your suggestion on retrieving the Assembly for a subclass of a given type by way of GetType() in an instance method instead of a static. I was hoping it would be possible in a single static method for use by the other developers on the team, but there are other ways to simplify the implementation. Thank you very much!
wintondeshong