Csharp/CSharp Tutorial/Class/public
Public vs private access
It is OK for a member of a class to access a private member of the same class.
<source lang="csharp">using System;
class MyClass {
private int a; // private access explicitly specified int b; // private access by default public int gamma; // public access public void setAlpha(int val) { a = val; } public int getAlpha() { return a; } public void setBeta(int a) { b = a; } public int getBeta() { return b; }
}
class AccessDemo {
public static void Main() { MyClass ob = new MyClass(); /* Access to a and b is allowed only through methods. */ ob.setAlpha(-99); ob.setBeta(19); Console.WriteLine("ob.a is " + ob.getAlpha()); Console.WriteLine("ob.b is " + ob.getBeta()); // You cannot access a or b like this:
// ob.a = 10; // Wrong! a is private! // ob.b = 9; // Wrong! b is private!
// It is OK to directly access gamma because it is public. ob.gamma = 99; }
}</source>
ob.a is -99 ob.b is 19
Re-using Base Class Identifiers
<source lang="csharp">class Point2D {
public int X; public int Y;
}
class Point3D : Point2D {
public int X; public int Y; public int Z;
}
class MyMainClass {
public static void Main() { Point2D My2DPoint = new Point2D(); Point3D My3DPoint = new Point3D(); My2DPoint.X = 100; My2DPoint.Y = 200; My3DPoint.X = 150; My3DPoint.Y = 250; My3DPoint.Z = 350; }
}</source>
Use an access modifier with an accessor
<source lang="csharp">using System;
class MySequence {
int prop; public MySequence() { prop = 0; } public int MyProp { get { return prop; } private set { // private prop = value; } } public void increaseSequence() { MyProp++; }
}
class MainClass {
public static void Main() { MySequence ob = new MySequence(); Console.WriteLine("Original value of ob.MyProp: " + ob.MyProp); ob.increaseSequence(); Console.WriteLine("Value of ob.MyProp after increment: " + ob.MyProp); }
}</source>
Original value of ob.MyProp: 0 Value of ob.MyProp after increment: 1