Consider the following classes:
public class Vehicle { ... }
public class Coverage { ... }
public class VehicleList : IEnumerable<Vehicle> { ... }
public class CoverageList : IEnumerable<Coverage> { ... }
public abstract class Quote
{
protected VehicleList vehicles;
protected CoverageList coverages;
internal Quote() { ... }
public IReadOnlyCollection<Vehicle> Vehicles
{
get { return this.vehicles.AsReadOnly(); }
}
public IReadOnlyCollection<Coverage> Coverages
{
get { return this.coverages.AsReadOnly(); }
}
...
}
public sealed class OhQuote : Quote
{
//needs to access protected fields
...
}
public sealed class InQuote : Quote { ... }
public sealed class MiQuote : Quote { ... }
Quote
fully encapsulates the functionality of both VehicleList
and CoverageList
so I'd like to mark those classes as internal
. The problem is that they are the types of protected
fields of a public
class. If I mark those fields as protected internal
then they are protected
OR internal
. What I really need is for them to be protected
AND internal
(with protected
taking precedence within the assembly). You can see that neither Quote
(which has an internal
constructor) nor its subclasses (which are sealed
) can be extended outside the assembly. I've already figured out how to achieve the desired functionality using public interfaces but wanted to make sure there's not a more concise way.
protected internal: The type or member can be accessed by any code in the assembly in which it's declared, or from within a derived class in another assembly. private protected: The type or member can be accessed by types derived from the class that are declared within its containing assembly.
The protected internal keyword combination is a member access modifier. A protected internal member is accessible from the current assembly or from types that are derived from the containing class. For a comparison of protected internal with the other access modifiers, see Accessibility Levels.
The type or member can be accessed by any code in the same assembly, but not from another assembly. protected internal: The type or member can be accessed by any code in the assembly in which it is declared, OR from within a derived class in another assembly.
Only the member functions or the friend functions are allowed to access the private data members of a class. The class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class. Private member are not inherited in class.
Although the .NET runtime supports this concept ("FamilyAndAssembly"), C# currently does not.
This was proposed for C# 6.0 in the form of the private protected access modifier, but the feature was dropped.
UPDATE: private protected
was added to C# 7.2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With