Wednesday, December 3, 2008

Default Access specifier for Classes and Methods in C#:

  • Default access specifier for class is public;
  • Default access specifier for method is private;

In C#, this has all changed. We can append our class declarations with class access modifiers to restrict both access to its internal members and methods, as well as instantiation rights. These eight access specifiers are:

  1. public: This class is accessible to all other classes. If a class is declared without explicitly specifying an access modifier for it, then it's public by default.
  2. private: Accessible only by the class in which it is declared.
  3. protected: Accessible only by the class in which it is declared, as well as any derived classes.
  4. protected internal: Accessible only by the class in which it is declared, as well as any derived classes in the same source code file.
  5. internal: Accessible only from within the same assembly (in C#, an assembly is a package of inter-related data that contains both code and meta data).
  6. sealed: Prevents a class from every being derived. If another class tries to use this class as its base class either directly or indirectly then the C# compiler will raise an error.
  7. abstract: Similar to the concept of a pure virtual function in C++, an abstract class can't actually be instantiated. It contains a signature, but can only be used when it is the base class of a derived class.
  8. new: Using the new keyword as an access modifier for a nested class allows us to hide an inherited method of a parent class by providing the compiler with a new version of that class.

No comments: