What is Public Access Modifier in C#?

You can associate public access modifier to a type or any members of the type.



Members with access modifier as public can be accessed by any class belonging to any project. This modifier provides the higher level of visibility.

Consider the following example:

public class sampleClass {
public int member1;
public sampleClass(int member1) {
this.member1 = member1;
}
}
public class testClass {
public static void Main() {
sampleClass obj = new sampleClass(10);
Console.WriteLine(“obj.member1={0}”, obj.member1);
obj.member1 = 100;
Console.WriteLine(“After update: obj.member1={0}”, obj.member1);
}
}

Output of this code will be:

obj.member1=10
After update: obj.member1=100

In this example, you have created two classes namely sampleClass and testClass. You have associated public modifier with these classes. You have also marked their members as public. Since member1 is a public member of sampleClass, it can be directly accessed from any class using an instance of sampleClass. This is demonstrated inside Main method of testClass, where in you create an instance of sampleClass and you perform read and write operations on member1 directly.

| 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? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

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

Copyright - © 2004 - 2024 - All Rights Reserved.