This question is similar to c# internal abstract class, how to hide usage outside but my motiviation is different. Here is the scenario
I started with the following:
internal class InternalTypeA {...}
public class PublicClass
{
private readonly InternalTypeA _fieldA;
...
}
The above compiles fine. But then I decided that I should extract a base class and tried to write the following:
public abstract class PublicBaseClass
{
protected readonly InternalTypeA _fieldA;
...
}
And thus the problem, the protected member is visible outside the assembly but is of an internal type, so it won't compile.
The issue at hand is how to I (or can I?) tell the compiler that only public classes in the same assembly as PublicBaseClass may inherit from it and therefore _fieldA will not be expossed outside of the assembly?
Or is there another way to do what I want to do, have a public super class and a set of public base classes that are all in the same assembly and use internal types from that assembly in their common ("protected") code?
The only idea I have had so far is the following:
public abstract class PublicBaseClass
{
private readonly InternalTypeA _fieldA;
protected object FieldA { get { return _fieldA; } }
...
}
public class SubClass1 : PublicBaseClass
{
private InternalTypeA _fieldA { get { return (InternalTypeA)FieldA; } }
}
public class SubClass2 : PublicBaseClass
{
private InternalTypeA _fieldA { get { return (InternalTypeA)FieldA; } }
}
But that is UGLY!
In C# you can use the sealed keyword in order to prevent a class from being inherited. Also in VB.NET you can use the NotInheritable keyword to prevent accidental inheritance of the class.
Because a sealed class cannot be inherited, it cannot be used as base class and by consequence, an abstract class cannot use the sealed modifier.
protected (C# Reference) The protected keyword is a member access modifier. This page covers protected access. The protected keyword is also part of the protected internal and private protected access modifiers. A protected member is accessible within its class and by derived class instances.
The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
The CLR provides a FamilyAndAssembly accessibility which will do what you want, but there isn't the syntax in C# to use it.
The workaround is to make the variable field internal, and you'll have to trust the code in your assembly to not access it inappropriately.
You can also make the constructor of PublicBaseClass internal, so only your assembly can instantiate it. That way, only your classes can inherit off it (even if the class itself is public)
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