views:

24

answers:

2

Odd situation... I need to create a new instance of a class that needs a member of the calling class. But i can't pass a reference to the calling class through the constructor.

The solution i am looking for is something like this:

Public Class ChildClass
    Public Sub New(args)
        _MyMember = GetMemberFromCallingClass()
        ...
        ...
    End Sub
End Class

I want this to work without having to manually pass any references or variables from the calling class to the new instance of ChildClass.

Is this possible and if so, what should i look at to make this part of my code.

A: 

You do something like the code below to get the type of the calling class:

Dim trace As New System.Diagnostics.StackTrace()
System.Diagnostics.Debug.WriteLine(trace.GetFrame(1).GetMethod().ReflectedType.Name)

You can then call GetMethods or 'GetMember' or similar on the reflected type to get out the actual method you want.

Please note though, I think the ReflectedType will always return the base class, so this might not work properly if your method got called from a child class, but can't remember for sure.

ho1
I guess this is as close as it gets... Taking Brian Gideons reply into account i can get the type of caller but not the actual caller Thanks for the info!
Cadde
A: 

If by member you mean that you want to call a property or method on the actual instance of the calling class then no you cannot do that. The best you can do is walk the stack via StackTrace to extract the type information of the calling class, but you will not be able to extract the actual instance. If you want code in another class to have access members of a specific instance of another class then you will have to pass that reference around.

Brian Gideon