views:

65

answers:

1

Let's consider the following code :

    internal class FooInternal
    {
        internal static void DoIt()
        {
            throw new NotImplementedException();
        }
    }

Now i have a library inside which it is reflecting the FooInternal type and for a reflected methodInfo (in this case DoIt) i have this :

        if ((methodInfo.Attributes & MethodAttributes.FamANDAssem) 
               == MethodAttributes.FamANDAssem)
        {
              // hits here.
        }

We can see that i am hitting the line for an internal method that is marked as FarmAndAssem. Now, I also need to ensure that the method is delared in the same assembly from where it is invoked so that my libary does not end up hitting the line for members from type defined in other assembly and marked as internal.

I can't use Assembly.GetExecutingAssembly from within the library that reflects the method as it will return the assembly where the library resides not the assembly where type the is declared / invoked using the library.

Therefore, the code should ensure the following workflow:

 Given: FooInternal is declared in the same asssembly as the caller's assembly. 
 When: Called with MyLib.Fake(typeof(FooInternal)); 
 Then: It will hit the expected line.
 Given: A third-party type. 
 When: Called with MyLib.Fake(typeof(FileInfo)); 
 Then: It will not hit  the expected line even though *FileInfo* 
 has internal methods and as such the first condition passes, because 
 FileInfo belongs to a different assembly from caller's.

+5  A: 

You can get the assembly from the type in which your code is: this.GetType().Assembly and compare it to methodInfo.Module.Assembly.

Fredrik Mörk
Unfortunately, i guess it is bit different. Lets say i have a call MyLibrary.Fake<FooInternal>(), inside the Fake method,i add interceptor for methods in FooInternal, now as DoIt is also available (FarmAndAssembly) from its lets say test method, i need consider that as well but what is the case if I called it using a thirdparty type. In that case, i have to make a check whether there is an access from the calling method in that case the test method to the target type.
Mehfuz
@Mehfuz: you can just replace `this.GetType()` with the `Type` object that you wish to be your reference point. Inside `Fake<T>()` you can instead use `typeof(T).Assembly` to get the `Assembly` in which the type for the generic type parameter is declared.
Fredrik Mörk
@Fedrik: Thanks for the reply.Acutally, i already know the type via methodInfo.Module.Assembly, what i need to know here is that whether typeof(T).Assembly / methodInof.Module.Assembly resides in the same assembly that test or calling method resides. Til then i will process the internal method as internal methods can only be accessed (strongly) from members from its own asssembly.
Mehfuz