I have an abstract class for a device that includes a serial port:
public abstract class SerialDevice
{
// serial port (should this be protected, internal, or protected internal?)
protected SerialPort _serialPort;
// The serial port has some shared methods.
public void Open()
{
_serialPort.Open();
}
}
Derived classes also use the serial port, but I don't want the port visible outside of those derived classes.
public class Widget : SerialDevice
{
// The serial port has some widget-specific functionality.
public void UniqueCommand()
{
_serialPort.WriteLine("Hello world.");
}
}
When I compile, I get this warning: CA1051: Do not declare visible instance fields, which says that fields should be a hidden implementation detail. Ok, I can use a protected property instead and safeguard my classes against changes that break stuff.
But it goes on to recommend fields be private or internal. The C# Programming Guide's page on Access Modifiers says that making the serial port "protected" allows it to be accessed only within derived classes, while making it "internal" would allow it to be accessed within the whole assembly. So why is "internal" acceptable, but "protected" isn't? Isn't protected access less visible than internal access?
Related question: What should the accessablity of Fields in a Abstract Class be?