Access modifiers are keywords used to specify the declared accessibility of a member or a type. This section introduces the four access modifiers:
- public
- protected
- internal
- Protected internal
- private
The following six accessibility levels can be specified using the access modifiers:
- public: Access is not restricted.
- protected: Access is limited to the containing class or types derived from the containing class.
- internal: Access is limited to the current assembly.
- protected internal: Access is limited to the current assembly or types derived from the containing class.
- private: Access is limited to the containing type.
- private protected: Access is limited to the containing class or types derived from the containing class within the current assembly.
C# Public Access Specifier
using System;
namespace AccessSpecifiers
{
class PublicTest
{
public string name = "Shantosh Kumar";
public void Msg(string msg)
{
Console.WriteLine("Hello " + msg);
}
}
class Program
{
static void Main(string[] args)
{
PublicTest publicTest = new PublicTest();
// Accessing public variable
Console.WriteLine("Hello " + publicTest.name);
// Accessing public function
publicTest.Msg("Peter Decosta");
}
}
}
C# Protected Access Specifier
using System;
namespace AccessSpecifiers
{
class ProtectedTest
{
protected string name = "Rahul";
protected void Msg(string msg)
{
Console.WriteLine("Hello " + msg);
}
}
class Program
{
static void Main(string[] args)
{
ProtectedTest protectedTest = new ProtectedTest();
// Accessing protected variable
Console.WriteLine("Hello "+ protectedTest.name);
// Accessing protected function
protectedTest.Msg("Hello1");
}
}
}
C# Internal Access Specifier
using System;
namespace AccessSpecifiers
{
class InternalTest
{
internal string name = " Kumar";
internal void Msg(string msg)
{
Console.WriteLine("Hello " + msg);
}
}
class Program
{
static void Main(string[] args)
{
InternalTest internalTest = new InternalTest();
// Accessing internal variable
Console.WriteLine("Hello " + internalTest.name);
// Accessing internal function
internalTest.Msg("NEW Hello");
}
}
}
C# Protected Internal Access Specifier
using System;
namespace AccessSpecifiers
{
class InternalTest
{
protected internal string name = "Kumar";
protected internal void Msg(string msg)
{
Console.WriteLine("Hello " + msg);
}
}
class Program
{
static void Main(string[] args)
{
InternalTest internalTest = new InternalTest();
// Accessing protected internal variable
Console.WriteLine("Hello " + internalTest.name);
// Accessing protected internal function
internalTest.Msg("NEW Hello");
}
}
}
0 comments:
Post a Comment