locked
Internal access modifier RRS feed

  • Question

  • User-1963854939 posted

    I know what is the use of the internal access modifier and also how we can use the  InternalsVisibleToAttribute attribute to make our internal classes accessible outside the assembly.

    I have one confusion. How can we make only some classes of a namespace to be accessible outside the assembly i.e if I have 5 internal classes in a namespace, then how can I make 3 of them accessible outside the assembly. If i add the InternalsVisibleToAttribute attribute on 3 of these classes, I get the following warning :

    'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored.

    Also, it doesn't seems to work and the classes are not accessible outside the assembly.

    Is that we need to add 2 different namespace's, one for the classes which we need to expose and other for classes which we do not want to ?

    Saturday, July 5, 2014 12:54 PM

All replies

  • User-1818759697 posted

    Hi,

    InternalsVisibleToAttribute Class Specifies that types that are ordinarily visible only within the current assembly are visible to a specified assembly.

    In any class of MyAssembly, you can add something like

    [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyAssembly.UnitTest")]

    Note here this assembly attribute has to be declared outside your own namespace. For example, the following declaration will give you compilation error.

    namespace MyAssemblyNamespace
    
    {
    
          [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyAssembly.UnitTest")]
    
          public class A 
    
         {
    
             blah...
    
          }
    
    }
    

    Compiler will give you the following error

         assembly is not a valid attribute location for this declaration, valid attribute location is type.

    Now if you move the attribute outside your own namespace, it will start to work:

    [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyAssembly.UnitTest")]
    
    namespace MyAssemblyNamespace
    
    {
    
          public class A 
    
         {
    
             blah...
    
          }
    
    }
    

    Regards

    Monday, July 7, 2014 9:49 PM
  • User-1963854939 posted

    Thanks for the example Shawn.

    But my question is that can we have 5 classes (3 internal + 2 public). Then, if I would like to enable access to only one of the 3 internal classes out of two, then is that possible under one namespace or we need to have multiple namespaces ?

    Tuesday, July 8, 2014 11:03 AM
  • User753101303 posted

    Hi,

    It seems to be an assembly level attribute so it should be valid for all 3 or none (or then you would have to split this accross assemblies). I've never been a big fan of tweaking visibility this way.

    Wednesday, July 9, 2014 5:39 AM