C# Classes Part 2


A class. The namespace is Ch10Mike01

class Program  {    // Classes
    static void Main(string[] args)    {
        int i;
        i = PorterClass.MyStaticInt;
        WriteLine($"MyStaticInt is {i}. No need to instantiate class");  // no instantiate class
        WriteLine(PorterClass.GetStaticString());   // no instantiate class
        PorterClass myClass = new PorterClass();  // instantiate class
        WriteLine(myClass.GetString() + " and an integer " + myClass.MyROInt);
        ReadKey();  // pause execution awaiting keystroke
    }
}
class PorterClass  {
    public readonly int MyROInt = 10;
    public static int MyStaticInt = 12;  // accessed through the class: PorterClass.MyStaticInt
    private int myInt;  // since private, external code must use the property
    public int MyIntProperty
    {
        get { // the get and set blocks are known as "accessors"
            // property get code here. Read-only access.
            return myInt; }
        set { // propertry set code here. Should use try...catch...finally logic here 
            myInt = value; }
    }
    public string GetString() { return "string of public GetString()"; }
    public static string GetStaticString() { return "string of public static GetStaticString()"; }
    public PorterClass() { /* constructor code goes here */ }
    ~PorterClass()  {  /* destructor code goes here. Use the tilde character. */  }
}

This program produces three lines of code in the console (command line):
MyStaticInt is 12. No need to instantiate class
string of public static GetStaticString()
string of public GetString() and an integer 10

Leave a comment

Your email address will not be published. Required fields are marked *