Reputation: 985
How do you get the namespace of a method that has called the current public method?
I'm aware of how to find a calling method's name, but this is eluding me.
So here's an analogy of what I need for my Automated test solution in C#:
There are two cs files in "ExampleSolution.sln". Each of these class libraries has a single namespace. Namespace "1" and namespace "A".
Both namespaces have a single class and a single method.
Namespace 1 contains the method "LogIn", while Namespace A contains the method "MyTest".
MyTest calls LogIn at the start to perform a log in process. Inside of LogIn, code should determine the namespace of the calling method, MyTest. Therefore the string name of Namespace A should be returned as "A" to the LogIn method under Namespace 1.
The reason I want this is that the solution is structured in a way that valuable component information exists that can be used to determine a few variable's values without having to have these values passed in as arguments to the LogIn method each time it is called, which is hundreds of times.
Any help with this is greatly appreciated.
Upvotes: 0
Views: 948
Reputation: 56586
You shouldn't try to inspect the calling method's namespace. As Jon Skeet once said:
Just using the namespace of the class containing the calling method sounds brittle, unfriendly to tests, and generally a bad idea.
Instead, you might pass the data into your method. Keeping it contained within an object would let you keep the code clean, fast, and testable.
public interface IContext
{
string SomeVariable { get; }
int SomethingElse { get; }
}
public void LogIn(string user, IContext loginContext) { ... }
public class MyTestContext : IContext
{
private MyTestContext() { }
// TODO make this a singleton?
public static MyTestContext Instance { get { return new MyTestContext(); } }
public string SomeVariable { get { return "abc"; } }
public int SomethingElse { get { return 2; } }
}
Upvotes: 0
Reputation: 1017
You can also use http://msdn.microsoft.com/en-us/library/4ce0ktkk(v=vs.110).aspx to get the current stack information. You can navigate to how far back you want to go in the call stack using "GetFrame", and use those results to get information about the caller, including its "Type", and then it's "Namespace".
Upvotes: 0
Reputation: 12966
Have a look at Caller Information
By using Caller Info attributes, you can obtain information about the caller to a method. You can obtain file path of the source code, the line number in the source code, and the member name of the caller. This information is helpful for tracing, debugging, and creating diagnostic tools.
Assuming your folder structure maps to your namespacing, you can use CallerFilePathAttribute
to get the namespace without having to use Reflection to get it.
Upvotes: 1