What is Private Access Modifier in C# (C Sharp)?

Private access modifier provides the most restricted access.




If you define a member of a class as private then you can access the member only within the class. You cannot access it from outside the class.

Consider the following example:

public class sampleClass {
private int member1;
public sampleClass(int member1) {
this.member1 = member1;
}
public void displayMember1() {
Console.WriteLine(“Member1 = {0}”, member1);
}
}
public class testClass {
public static void Main() {
sampleClass obj = new sampleClass(10);
Console.WriteLine(“obj.member1={0}”, obj.member1);
}
}

In this example, you have a public class called sampleClass. Member of sampleClass named member1 is defined with private access modifier, which means that it cannot be accessed outside the class. But you try to access it in Main method of testClass. This is not permissible and so you will end up in the following error during execution of this code:

“‘sampleClass.member1’ is inaccessible due to protection level”

However, you can display the value of private member member1 using the following line of code: obj.displayMember1();

_______________________________________________________________________

Add to My Yahoo!


FREE Subscription

Subscribe to our mailing list and receive new articles
through email. Keep yourself updated with latest
developments in the industry.

Name:
Email:

Note : We never rent, trade, or sell my email lists to
anyone. We assure that your privacy is respected
and protected.

Visit .NET Programming Tutorial Homepage

______________________________________________________

Recommended Resource

| What is Private Access Modifier in C#? | What is Protected Access Modifier in C#? | What is Protected Internal Access Modifier in C#? | What is Public Access Modifier in C#? | What is the difference between virtual and abstract keywords in .NET? | What is the importance of Microsoft Application Blocks in .NET Architecture? | What is the need for Factory Method in C# | What is the purpose of ArrayList in .NET? | What is the purpose of Datareader in ADO.NET? | What is the purpose of Dataset in ADO.NET? | What is the purpose of finally block in C#? | What is the purpose of interlocked class in .NET? | What is the purpose of main() function in C# | What is the purpose of ManualResetEvent in .NET? | What is the purpose of sealed method in C#? | What is the purpose of Thread.Join() method in .NET? | What is the purpose of Thread.Sleep() method in .NET? | What is the purpose of throw keyword in C#? | What is the usage of ENUM in .NET? |


| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2017 - All Rights Reserved.