It looks to me that you might misunderstand the
DeclaringType
. No wonder your class's
DeclaringType
returns
null
— this is the only expected and correct result.
The thing is:
DeclaringType
is the property
applicable only to the members of some type. For example, enumeration member will have this property returning the type of enumeration type, a method will have this property returning the type of a class or a structure, etc.
Please see look at the MSDN page on this property more thoroughly, also pay attention for the code sample at the end:
http://msdn.microsoft.com/en-us/library/system.type.declaringtype.aspx[
^].
The only case when this property will return non-null value for a class would be a nested class. Consider this:
class Outer {
internal class Inner { }
}
class Test {
internal void Execute() {
Type type = typeof(Outer.Inner);
Type outer = type.DeclaringType;
Type outerDeclarer = typeof(Outer).DeclaringType;
}
}
So, your problem is different (and not quite clear so far, despite of your update). Please sort out by yourself what to do with all that, but you say "to get the type of an object that declares another object". Now, object is not its type. The object is represented by the
MemberInfo
of the declaring type (
FieldInfo
,
PropertyInfo
…). These member information types will certainly return correct declaring type if you call their
DeclaringType
property. But! — neither instance (object itself) nor its type is aware of the fact which member it is. The member information is the attribute of the declaring type, but if you already know declaring type, why would you make a round trip to calculate it? Are you getting the picture?
Now, I have a feeling that your problem is still solvable, but you are approaching it from the wrong side. Chances are, my explanations can help you to get the right idea. If not, I would need to get much wider information on your application, all the ins and outs related to your problem, really good detail on you goals and on what you are going to do with this type when you find it.
—SA