Defining Member and Type Visibility - Type Visibility
(Page 6 of 6 )
Public Type
Creating a public type means that the type is accessed from other types in the current assembly as well as other assemblies. This is useful when you are creating a code library. Here is an example:
public class Book
{
private string title;
private string author;
private string ISBN;
…
}
Since the Book class is public, it can be accessed from other assemblies. The users of this assembly can create Book objects, inherit from the Book class, and so on…
Internal Type
Internal types, on the other hand, can be used only by the assembly in which they are defined. So, if we make the Book class internal, other assemblies cannot in any way interact with the Book class:
internal class Book
{
private string title;
private string author;
private string ISBN;
…
}
Please note that the default access modifier for a type is internal. In other words, if you do not specify the access modifier, it will be internal. So the following declarations are identical:
class Book {...}
internal class Book {...}
Conclusion
When creating types, it is very important to pay special attention to the type member’s visibility. Declaring a member private makes it accessible only to the defining class. Declaring the member public, on the other hand, makes it accessible by any type. When it comes to inheritance, try to keep members protected so that only subclasses can access them. As far as building your own libraries, internal and protected internal members come handy.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |