Is it possible to have internal-like access modifier at instantiation rather than declaration?

StackOverflow https://stackoverflow.com/questions/19384039

  •  30-06-2022
  •  | 
  •  

Question

In the following scenario (excuse my pseudocode):

Assembly Lib:
   Interface A;
   Class 123; //Utilizes multiple properties with a { get; internal set; } pattern.

   //Contains more class definitions like Class 123

Assembly Impl: //References Lib 
   Class MyImpl; //Implements Interface A and utilizes Class 123.


ClientApplication:
   //Consumes Interface A

I was wondering if there is a way to allow Class MyImpl to access the property set() of Class 123 without using statically declared friend assemblies and keeping those set() also hidden from the ClientApplication.

The end goal is to be able to deploy this in a manner that allows ClientApplication to utilize the types from AssemblyLib, and being able to drop new implementation assemblies without having to recompile and redistribute Assembly Lib.

I was thinking something along the likes of finding a way to make the internal modifier take effect at its instantiation (Assembly Impl) rather than at its declaration (Assembly Lib) but I dont believe that C# supports anything like this.

I realize this is probably really ugly if it can be done, and I am not sure myself that it can regardless, but alas that is why I am here! Thanks for your help in advance.

Was it helpful?

Solution

  1. You could use reflection to access the internals of Lib. This isn't a very nice solution.
  2. You could make Impl a friend assembly of Lib. This isn't a very nice solution.
  3. You could restructure your design to fix the need for Impl to access Lib's internals. This is the nice solution.

Using your example, here is an idea of what I'm getting at. Why not change the design to:

Assembly Lib:
   Interface A;
   Interface B; //Utilizes multiple properties with a { get; } pattern.

   //Contains more interface definitions like Interface B

Assembly Impl: //References Lib 
    Class 123; //Utilizes multiple properties with a { get; internal set; } 
               //pattern. Implements B.

    //Contains more class definitions like Class 123

    Class MyImpl; //Implements Interface A and utilizes Class 123.

ClientApplication:
    //Consumes implementations of Interface A and B provided by Impl.

OTHER TIPS

You might want to look at the InternalsVisibleToAttribute for this.

For example, in your Lib assembly, add this line to your assemblyinfo.cs file:

[assembly:InternalsVisibleTo("Impl")]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top