How to use the Public access modifier of C #
Today Xiaobian to share with you how to use the C#Public access modifier related knowledge points, detailed content, clear logic, I believe most people still know too much about this knowledge, so share this article for everyone to refer to, I hope you read this article after some harvest, let's learn about it together.
Public access modifier
The Public access modifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed by external classes.
The following examples illustrate this:
using System;
namespace RectangleApplication
{
class Rectangle
{
//Member variables
public double length;
public double width;
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}// Rectangle ends
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following results:
Length: 4.5 Width: 3.5 Area: 15.75
In the example above, the member variables length and width are declared public, so they can be accessed by the function Main() using an instance r of the Rectangle class.
The member functions Display() and GetArea() have direct access to these variables.
The member function Display() is also declared public, so it can also be accessed by Main() using an instance r of the Rectangle class.
The above is "C#Public access modifier how to use" all the content of this article, thank you for reading! I believe everyone has a great harvest after reading this article. Xiaobian will update different knowledge for everyone every day. If you want to learn more knowledge, please pay attention to the industry information channel.