Question

This is a follow-up for this question.

I have a security sensitive class A and a hierarchy of wrappers that use it (classes B and ChildOfB). B must initialize an instance of A and allow ChildOfB to use it. The instance of A should be accessible only to B and ChildOfB, which is exposed to other assemblies and can not be internal.

The code sample:

// ************* Library assembly *************
internal class A {}

public abstract class B
{
    // compiler error: Inconsistent accessibility: property type 
    // 'Library.A' is less accessible than property 'Library.B.Property'    
    protected A Property { get; private set; }
}

public sealed class ChildOfB : B
{
    public ChildOfB()
    {
        Console.WriteLine(Property);
    }
}


// ************* in some other assembly *************
var wrapper = new ChildOfB();

As far as I know there is no way to do it in plain C#. I am OK with a solution that uses an external tool, that might modify a dll after compilation (for example based on some attributes). For example in my code the property will be internal instead of protected and after the compilation this tool may change CLR type definition to include missing flags (the result should have family and assembly access modifier). It also would be great if this tool insures that changing property's access modifiers does not break any code in the initial dll.

Was it helpful?

Solution 2

Since C# 7.2 there is construct private protected (link) that does the job.

OTHER TIPS

If this is only about preventing accidental mistakes, not about security, you could use a static analyzer to enforce this rule. Set the visibility to internal and have the analyzer emit a warning/error when those classes are used in ways you don't like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top