Fundamentals of Staticity

Introduction

Consider a class as follows:

public class Chemistry
{
}

If you have a class, to access it outside its body, you can declare a variable of it as we have done so far. In the same way, you can declare various instances of the same class. Here are examples:

// A variable of the class
Chemistry chem = new Chemistry();

// Another variable of the class
Chemistry item = new Chemistry();

public class Chemistry
{
}

A variable you have declared of a class is also called an instance of the class. Each instance gives you access to the members of the class but each instance holds the particular values of the members of its instance. All the member variables and methods of classes we have used so far are referred to as instance members because, in order to access them, you must have an instance of a class declared in another class in which you want to access them.

In your application, you can declare a variable and refer to it regardless of which instance of an object you are using. Such a variable is referred to as static.

Practical LearningPractical Learning: Introducing Staticity

  1. Start Microsoft Visual Studio and create a Console App that supports the .NET 7.0 (Standard Term Support) named Chemistry5
  2. To create a new folder, in the Solution Explorer, right-click Chemistry5 -> Add -> New Folder
  3. Type Models as the name of the folder
  4. In the Solution Explorer, right-click Models -> Add -> Class...
  5. Change the file name to Element
  6. Click Add
  7. Change the document and class as follows:
    namespace Chemistry5.Models
    {
        public enum Phase { Gas, Liquid, Solid, Unknown }
    
        public class Element
        {
            internal string ElementName  { get; set; }
            internal string Symbol       { get; set; }
            internal int    AtomicNumber { get; set; }
            internal double AtomicWeight { get; set; }
            internal Phase  Phase        { get; set; }
    
            public Element()                 { }
            public Element(string symbol) => Symbol = symbol;
            public Element(int number)    => AtomicNumber = number;
    
            public Element(int number, string symbol, string name, double mass, Phase phase)
            {
                ElementName  = name;
                AtomicWeight = mass;
                Phase        = phase;
                Symbol       = symbol;
                AtomicNumber = number;
            }
        }
    }
  8. In the Solution Explorer, right-click Program.cs and click Rename
  9. Type PeriodicTable (to get PeriodicTable.cs) and press enter
  10. Read the text in the message box and press Enter twice (to accept the name and access the document)
  11. Click the PeriodicTable.cs tab and change the document as follows:
    using Chemistry5.Models;
    using static System.Console;
    
    void Present(Element obj)
    {
        WriteLine("Chemistry");
        WriteLine("--------------------------");
        WriteLine("Symbol:        " + obj.Symbol);
        WriteLine($"Atomic Number: {obj.AtomicNumber}");
        WriteLine("Element Name:  " + obj.ElementName);
        WriteLine($"Atomic Weight: " + obj.AtomicWeight);
        WriteLine("Phase/State:   " + obj.Phase);
        Write("==========================");
    }
    
    Element Prepare()
    {
        Element h  = new(1, "H", "Hydrogen", 1.008, Phase.Gas);
        Element he = new(2, "He", "Helium", 4.002602, Phase.Gas);
        Element li = new(3, "Li", "Lithium", 6.94, Phase.Solid);
        Element be = new(4, "Be", "Beryllium", 9.0121831, Phase.Solid);
        Element b  = new(5, "B", "Boron", 10.81, Phase.Solid);
        Element c  = new(name: "Carbon", mass: 12.011, symbol: "C", number: 6, phase: Phase.Solid);
        Element n  = new(7, "N", "Nitrogen", 14.007, Phase.Gas);
        Element o  = new(8, "O", "Oxygen", 15.999, Phase.Gas);
        Element f  = new(9, "F", "Fluorine", 18.998, Phase.Gas);
        Element ne = new(10, "Ne", "Neon", 20.180, Phase.Gas);
        Element na = new(11, "Na", "Sodium", 22.990, Phase.Solid);
        Element mg = new(12, "Mg", "Magnesium", 24.305, Phase.Solid);
        Element al = new() {Phase = Phase.Solid, Symbol = "Al", AtomicNumber = 13, ElementName = "Aluminium", AtomicWeight = 26.982 };
        Element si = new(14, "Si", "Silicon", 28.085, Phase.Solid);
        Element p = new() { Symbol = "P", AtomicWeight = 30.974, AtomicNumber = 15, ElementName = "Phosphorus", Phase = Phase.Solid };
        Element s = new(16, "S", "Sulfur", 32.06, Phase.Solid);
    
        return s;
    }
    
    Element elm = chem.Prepare();
    
    Present(elm);
  12. To execute, on the main menu, click Debug -> Start Without Debugging:
    Chemistry
    --------------------------
    Symbol:        S
    Atomic Number: 16
    Element Name:  Sulfur
    Atomic Weight: 32.06
    Phase/State:   Solid
    ==========================
    Press any key to close this window . . .

A Static Field

To declare a member variable of a class as static, that is, to create a static field, type the static keyword on its left. Here is an example:

public class Chemistry
{
    static string Category;  
}

In the same way, you can create as many static fields as you want. As we saw in previous lessons, you can control access to a field using a modifier (private, public, internal or protected). If you apply the modifier, the static keyword can be written before or after it, as long as it appears before the data type. Here are examples:

public class Chemistry
{
    public static int Period;
    static public int Group;
}

To access a static variable, you must "qualify" it where you want to use it. Qualifying a member means you must specify its class, followed by a period, and followed by the static field. Here are examples:

using static System.Console;

Car.make = "Ford";
Car.model = "Escort";

WriteLine("Vehicle Registration");
WriteLine("---------------------");
WriteLine("Make:  {0}", Car.make);
WriteLine("Model: {0}", Car.model);
WriteLine("======================");

public class Car
{
    public static string make;
    static public string model;
}

This would produce:

Vehicle Registration
---------------------
Make:  Ford
Model: Escort
======================

Press any key to close this window . . .

This means that when a field has been created as static, you don't need an instance of the class to access that member variable outside of the class. Based on this, if you declare all members of a class as static, you don't need to declare a variable of their class in order to access them.

In your class, you can create a combination of static and non-static fields if you judge it necessary. You just have to remember that, to access a static variable, you don't create an instance of the class. To access a non-static variable, you must declare a variable for the class. Here is an example:

using static System.Console;

Car cr = new Car();
Car.make = "Ford";
Car.model = "Escort";
cr.doors = 4;

WriteLine("Vehicle Registration");
WriteLine("---------------------");
WriteLine("Make:  {0}", Car.make);
WriteLine("Model: {0}", Car.model);
WriteLine("Doors: {0}", cr.doors);
WriteLine("======================");

public class Car
{
    public static string make;
    static public string model;
    public int           doors;
}

This would produce:

Vehicle Registration
---------------------
Make:  Ford
Model: Escort
Doors: 4
======================

Press any key to close this window . . .

You can create a method in a class. That method can directly access static and non-static members by their names. From a local method, a static field can be accessed either by its name or by qualifying it. Here are examples:

using static System.Console;

Residence res = new Residence();

res.Present();

class Residence
{
    public static int Bedrooms;
    static public double Bathrooms;
    public double MarketValue;
    public string ConstructionStatus;

    public void Present()
    {
        Bedrooms = 5;
        Residence.Bathrooms = 3.50;
        ConstructionStatus = "Needs Renovation";
        MarketValue = 545_825;

        WriteLine("==//== Altair Realtors ==//==");
        WriteLine("--------------------------------");
        Write("Number of Bedrooms:   ");
        WriteLine(Residence.Bedrooms);
        Write("Number of Bathrooms:  ");
        WriteLine(Residence.Bathrooms);
        Write("Construction Status:  ");
        WriteLine(ConstructionStatus);
        Write("Market Value:         $");
        WriteLine(MarketValue);
        WriteLine("================================");
    }
}

This would produce:

==//== Altair Realtors ==//==
--------------------------------
Number of Bedrooms:   5
Number of Bathrooms:  3.5
Construction Status:  Needs Renovation
Market Value:         $545825
================================

Press any key to close this window . . .

Introduction to Static Properties

A property can be made static. One option is to create the property in a normal class. Then write static on the left side of the data type of the property. If you are creating a property that controls the value of a property, the corresponding field must also be static. Here is an example:

using static System.Console;

Square sqr = new Square();

WriteLine("=====================================");
WriteLine("Enter the value to process the square");
Write("Side:       ");
Square.Side = double.Parse(ReadLine());

WriteLine("=====================================");
WriteLine("Square Values");
WriteLine("-------------------------------------");
WriteLine("Area:      {0}", sqr.Area);
WriteLine("Perimeter: {0}", Square.Perimeter);
WriteLine("=====================================");

public class Square
{
    private static double s;

    public Square()
    {
    }

    public static double Side
    {
        get { return s; }

        set { s = value; }
    }

    static public double Perimeter { get { return s * 4; } }

    public double Area { get { return s * s; } }
}

Here is an example of running the program

=====================================
Enter the value to process the square
Side:       248.77
=====================================
Square Values
-------------------------------------
Area:      61886.5129
Perimeter: 995.08
=====================================

Press any key to close this window . . .

A Static Enumerated Property

A property created from an enumeration can be created as a static property. To do this, on the left side of the type of the property, type the static keyword. Here are examples:

public enum Alignment
{
    FarLeft, Left, CenterLeft,
    Center,
    CenterRight, Right, FarRight
}

public class PoliticalParty
{
    private static Alignment align;

    static public Alignment Affiliation
    {
        get
        {
            return align;
        }

        set
        {
            align = value;
        }
    }

    public static Alignment Policy { get; set; }
}

Static Methods

Introduction

Like a field, a method of a class can be made static. Such a method can access any member of the class but it depends on how the member was declared. Remember that you can have static or non-static members of a class.

Creating a Static Method

To define a method as static, type the static keyword to its left. Here is an example:

public class Chemistry
{
    static void Display()
    {
    }
}

A static method can also use an access modifier. You can write the access modifier before or after the static keyword. Here is an example:

public class Chemistry
{
    public static void Display()
    {
    }
}

As mentioned for a static field, using a static method depends on where it is being accessed. To access a static member from a static method of the same class, you can just use the name of the static member. Here is an example:

public class Chemistry
{
    static private string Category;

    private static void Categorize()
    {
        Category = "Alkali Metal";
    }
}

You can also qualify the member by typing the name of the class, followed by a period, followed by the member. Here is an example:

public class Chemistry
{
    static private string Category;

    private static void Categorize()
    {
        Chemistry.Category = "Alkali Metal";
    }
}

To access a non-static member from a static method of the same class, you must declare a variable of the class and use it. Here is an example:

public class Residence
{
    public static int Bedrooms;
    static public double Bathrooms;
    public double MarketValue;
    public string ConstructionStatus;

    static public void Create()
    {
        Residence res = new Residence();

        Bedrooms = 5;
        Residence.Bathrooms = 3.50;
        res.ConstructionStatus = "Needs Renovation";
        res.MarketValue = 545_825;
    }
}

Details on Static Members

Introduction

In previous lessons, we saw various techniques to create methods in a class. Methods allow you to perform on members such as fields. In some cases, a certain method doesn't access any field of the class. In that case, when accessing such a method, there is no need to declare a variable of the class. Instead, you can make the method static and access it using the name of the class.

Practical LearningPractical Learning: Implementing Static Methods

  1. Change the PeriodicTable.cs document as follows:
    using Chemistry5.Models;
    using static System.Console;
    
    static void Present(Element obj)
    {
        WriteLine("Chemistry");
        WriteLine("--------------------------");
        WriteLine("Symbol:        " + obj.Symbol);
        WriteLine($"Atomic Number: {obj.AtomicNumber}");
        WriteLine("Element Name:  " + obj.ElementName);
        WriteLine($"Atomic Weight: " + obj.AtomicWeight);
        WriteLine("Phase/State:   " + obj.Phase);
        Write("==========================");
    }
    
    static Element Prepare()
    {
        Element h  = new(1, "H", "Hydrogen", 1.008, Phase.Gas);
        Element he = new(2, "He", "Helium", 4.002602, Phase.Gas);
        Element li = new(3, "Li", "Lithium", 6.94, Phase.Solid);
        Element be = new(4, "Be", "Beryllium", 9.0121831, Phase.Solid);
        Element b  = new(5, "B", "Boron", 10.81, Phase.Solid);
        Element c  = new(name: "Carbon", mass: 12.011, symbol: "C", number: 6, phase: Phase.Solid);
        Element n  = new(7, "N", "Nitrogen", 14.007, Phase.Gas);
        Element o  = new(8, "O", "Oxygen", 15.999, Phase.Gas);
        Element f  = new(9, "F", "Fluorine", 18.998, Phase.Gas);
        Element ne = new(10, "Ne", "Neon", 20.180, Phase.Gas);
        Element na = new(11, "Na", "Sodium", 22.990, Phase.Solid);
        Element mg = new(12, "Mg", "Magnesium", 24.305, Phase.Solid);
        Element al = new() {Phase = Phase.Solid, Symbol = "Al", AtomicNumber = 13, ElementName = "Aluminium", AtomicWeight = 26.982 };
        Element si = new(14, "Si", "Silicon", 28.085, Phase.Solid);
        Element p  = new() { Symbol = "P", AtomicWeight = 30.974, AtomicNumber = 15, ElementName = "Phosphorus", Phase = Phase.Solid };
        Element s  = new(16, "S", "Sulfur", 32.06, Phase.Solid);
        Element cl = new(17, "Cl", "Chlorine", 35.45, Phase.Gas);
    
        return cl;
    }
    
    Element elm = PeriodicTable.Prepare();
    
    PeriodicTable.Present(elm);
  2. To execute, on the main memu, click Debug -> Start Without Debugging:
    Chemistry
    --------------------------
    Symbol:        Cl
    Atomic Number: 17
    Element Name:  Chlorine
    Atomic Weight: 35.45
    Phase/State:   Gas
    ==========================
    Press any key to close this window . . .
  3. Close the window and return to your programming environment
  4. Click the Element.cs tab and change its class as follows:
    namespace Chemistry5
    {
        public enum Phase { Gas, Liquid, Solid, Unknown }
    
        public class Element
        {
            internal string ElementName  { get; set; }
            internal string Symbol       { get; set; }
            internal int    AtomicNumber { get; set; }
            internal double AtomicWeight { get; set; }
            internal Phase  Phase        { get; set; }
    
            public Element()                 { }
            public Element(string symbol) => Symbol = symbol;
            public Element(int number)    => AtomicNumber = number;
    
            public Element(int number, string symbol, string name, double mass, Phase phase)
            {
                ElementName  = name;
                AtomicWeight = mass;
                Phase        = phase;
                Symbol       = symbol;
                AtomicNumber = number;
            }
    
            public Element Ar = new Element(18, "Ar", "Argon", 39.948, Phase.Gas);
            public Element K = new Element(phase: Phase.Solid, number: 19, symbol: "K", name: "Potassium", mass: 39.098);
            public Element Ca = new(20, "Ca", "Calcium", 40.078, Phase.Solid);
            public Element Sc = new(number: 21, symbol: "Sc", phase: Phase.Solid, name: "Scandium", mass: 44.956);
            public Element Ti = new(name: "Titanium", number: 22, symbol: "Ti", mass: 47.867, phase: Phase.Solid);
            public Element V = new Element()
            {
                AtomicNumber = 23,
                Symbol = "V",
                AtomicWeight = 50.942,
                ElementName = "Vanadium"
            };
        }
    }

The Type of a Field as its Own Class

We already know that, in a class, you can create a field whose type is its own class. We also saw that you can initialize such a field in the body of the class. Such a field usually doesn't modify any member of its class. In this case, when accessing the field outside its class, you don't need an object of the class. As a result, you can/should make the field static.

Practical LearningPractical Learning: Creating a Field Whose Type is its Own Class

  1. Change the Element class as follows:
    namespace Chemistry5.Models
    {
        public enum Phase { Gas, Liquid, Solid, Unknown }
    
        public class Element
        {
            internal string ElementName  { get; set; }
            internal string Symbol       { get; set; }
            internal int    AtomicNumber { get; set; }
            internal double AtomicWeight { get; set; }
            internal Phase  Phase        { get; set; }
    
            public Element()                 { }
            public Element(string symbol) => Symbol = symbol;
            public Element(int number)    => AtomicNumber = number;
    
            public Element(int number, string symbol, string name, double mass, Phase phase)
            {
                ElementName  = name;
                AtomicWeight = mass;
                Phase        = phase;
                Symbol       = symbol;
                AtomicNumber = number;
            }
    
            public static Element Ar = new Element(18, "Ar", "Argon", 39.948, Phase.Gas);
            public static Element K = new Element(phase: Phase.Solid, number: 19, symbol: "K", name: "Potassium", mass: 39.098);
            public static Element Ca = new(20, "Ca", "Calcium", 40.078, Phase.Solid);
            public static Element Sc = new(number: 21, symbol: "Sc", phase: Phase.Solid, name: "Scandium", mass: 44.956);
            public static Element Ti = new(name: "Titanium", number: 22, symbol: "Ti", mass: 47.867, phase: Phase.Solid);
            public static Element V = new Element()
            {
                AtomicNumber = 23,
                Symbol = "V",
                AtomicWeight = 50.942,
                ElementName = "Vanadium"
            };
        }
    }
  2. Click the PeriodicTable.cs tab and change its document as follows:
    using static System.Console;
    
    namespace Chemistry5
    {
        public class PeriodicTable
        {
            static void Present(Element obj)
            {
                WriteLine("Chemistry");
                WriteLine("--------------------------");
                WriteLine("Symbol:        " + obj.Symbol);
                WriteLine($"Atomic Number: {obj.AtomicNumber}");
                WriteLine("Element Name:  " + obj.ElementName);
                WriteLine($"Atomic Weight: " + obj.AtomicWeight);
                WriteLine("Phase/State:   " + obj.Phase);
                WriteLine("==========================");
            }
    
            static Element Prepare()
            {
                // . . .
            }
    
            static void Main()
            {
                // Element elm = PeriodicTable.Prepare();
    
                PeriodicTable.Present(Element.Ar);
                PeriodicTable.Present(Element.K);
                PeriodicTable.Present(Element.Ca);
                PeriodicTable.Present(Element.Sc);
                PeriodicTable.Present(Element.Ti);
                PeriodicTable.Present(Element.V);
            }
        }
    }
  3. To execute, on the main menu, click Debug -> Start Without Debugging:
    Chemistry
    --------------------------
    Symbol:        Ar
    Atomic Number: 18
    Element Name:  Argon
    Atomic Weight: 39.948
    Phase/State:   Gas
    ==========================
    Chemistry
    --------------------------
    Symbol:        K
    Atomic Number: 19
    Element Name:  Potassium
    Atomic Weight: 39.098
    Phase/State:   Solid
    ==========================
    Chemistry
    --------------------------
    Symbol:        Ca
    Atomic Number: 20
    Element Name:  Calcium
    Atomic Weight: 40.078
    Phase/State:   Solid
    ==========================
    Chemistry
    --------------------------
    Symbol:        Sc
    Atomic Number: 21
    Element Name:  Scandium
    Atomic Weight: 44.956
    Phase/State:   Solid
    ==========================
    Chemistry
    --------------------------
    Symbol:        Ti
    Atomic Number: 22
    Element Name:  Titanium
    Atomic Weight: 47.867
    Phase/State:   Solid
    ==========================
    Chemistry
    --------------------------
    Symbol:        V
    Atomic Number: 23
    Element Name:  Vanadium
    Atomic Weight: 50.942
    Phase/State:   Gas
    ==========================
    
    Press any key to close this window . . .

Static Classes

Introduction

Like a variable or a method, a class can be made static. A static class:

Creating a Static Class

To create a static class, precede the class keyword with the static keyword. Based on the above two rules, all members of a static class must be made static. Here is an example:

public static class Region
{
    public static string Name;
    public static string States;
}

Accessing a Static Class

To use a static class, don't declare a variable of the class; that is, don't create an instance of the class. To access any member of the class, type the name of the class, a period, and the desired member. Here are examples:

public static class Region
{
    public static string Name;
    public static string States;
}

public class Statistics
{
    public void Create()
    {
        Region.Name = "New England";
        Region.States = "Connecticut, Maine, Massachusetts, New Hampshire, Rhode Island, and Vermont";

        string str = Region.Name;
        string stt = Region.States;
    }
}

In the above example, we created both the static and the non-static class in the same document. Of course, you can create each class in its own file. Here is an example of a file named Administration.cs that contains a static class:

public static class Management
{
    public static string Category;
    public static int WorkCode;
}

Using a Static Class

As another technique to access a static class, in the top section of the document where you want the static class, type using static followed by the name of the static class and a semicolon. Then, in the document, you can simply type the name of the member you want to access. Here is an example:

using static Management;

public class Workload
{
    public void Create()
    {
        Category = "Full-Time";
        string emplName = "Esther Garland";
        WorkCode = 927004;

        string cat = Category;
        string wc  = WorkCode.ToString();
    }
}

Static Constructors

Like a normal method, a constructor can be made static. There are rules you must follow. If you want to use a static constructor, you must explicitly create it (the compiler doesn't create a static constructor for you).

The static constructor must become the default constructor. That is, you must create a constructor that doesn't use any parameter. Here is an example:

public class Person
{
    public string firstName;

    static Person()
    {
    }
}

If you create a static constructor, you cannot directly access the non-static fields of the class:

Static Constructor

You can still access any field of the class as you see fit. Here are examples:

public class Person
{
    public string firstName;

    static Person()
    {
    }
}

public class Exercise
{
    static void Main()
    {
        Person pers = new Person();

        pers.firstName = "Gertrude";
    }
}

To use a static constructor, you have various options. To initialize a field in the static constructor, you can declare a variable of the class and access the member variable. Here is an example:

public class Person
{
    public string firstName;

    static Person()
    {
        Person pers = new Person();

        pers.firstName = "Gertrude";
    }
}

In reality, one of the reasons for using a static constructor is to initialize the static fields of the class or perform any action that would be shared by all instances of the class. Therefore, another option to use a static constructor is to initialize the static fields. After doing this, when accessing the initialized static field(s), it(they) would hold the value(s) you gave it(them). Here is an example:

public class Person
{
    public static string firstName;

    static Person()
    {
        firstName = "Gertrude";
    }
}

public class Exercise
{
    static void Main()
    {
        Person.firstName;
    }
}

Because the constructor is static, you cannot access it by declaring a variable of the class.

Another rule to observe with a static constructor is that you must not add an access modifier to it. The following will result in an error:

public class Person
{
    public static Person()
    {
    }
}

As mentioned already, you can create a class that uses a combination of a static constructor and one or more other (non-static) constructors. Here is an example:

public class Person
{
    static Person()
    {
    }

    public Person(string first, string last)
    {
    }
}

If you create such a class and if you want to declare a variable for it, the default constructor doesn't exist or is not available. If you want to declare a variable, you must use a constructor that uses a parameter. Here is an example:

Person pers = new Person("Gertrude", "Monay");
    
public class Person
{
    public string firstName;
    public string lastName;

    static Person()
    {
    }

    public Person(string first, string last)
    {
        firstName = first;
        lastName = last;
    }
}

Static Classes and Namespaces

Introduction

When creating a static class, you can include it in a namespace. Here is an example:

namespace BusinessManagement
{
    static class LoanApplicant
    {
        public static long AccountNumber = 402_924_759;
        public static string FullName = "Joseph Nyate";
    }
}

Using a Static Class of a Namespace

If the code where you want to access a static class is in the same namespace as the static class, you can use the class by its name. Here is an example:

using static System.Console;

WriteLine("Loan Application");
Write("Account #: ");
WriteLine(LoanApplicant.AccountNumber);
Write("Applicant Name: ");
WriteLine(LoanApplicant.FullName);

namespace BusinessManagement
{
    static class LoanApplicant
    {
        public static long AccountNumber = 402_924_759;
        public static string FullName = "Joseph Nyate";
    }
}

As we have learned, if the class was created in a namespace different from the area where you want to use it, one option is to fully qualify the name of the class. Here are examples:

using static System.Console;

WriteLine("Loan Application");
Write("Account #: ");
WriteLine(LoanApplicant.AccountNumber);
Write("Applicant Name: ");
WriteLine(LoanApplicant.FullName);
Write("Loan Amount: ");
WriteLine(Information.Evaluation.LoanAmount);
Write("Interest Rate: ");
Write(Information.Evaluation.InterestRate);
WriteLine("%");
Write("Perdiods: ");
Write(Information.Evaluation.Periods);
WriteLine(" Months");

namespace BusinessManagement
{
    static class LoanApplicant
    {
        public static int AccountNumber = 402_924_759;
        public static string FullName = "Joseph Nyate";
    }
}

namespace Information
{
    static class Evaluation
    {
        public static double LoanAmount = 2460;
        public static double InterestRate = 14.65; // %
        public static double Periods = 42d;
    }
}

Another option is to first add a using line that includes the static class's namespace, then use the name of the class. Here is an example:

using static System.Console;

using Information;

WriteLine("Loan Application");
Write("Account #: ");
WriteLine(LoanApplicant.AccountNumber);
Write("Applicant Name: ");
WriteLine(LoanApplicant.FullName);
Write("Loan Amount: ");
WriteLine(Evaluation.LoanAmount);
Write("Interest Rate: ");
Write(Evaluation.InterestRate);
WriteLine("%");
Write("Perdiods: ");
Write(Evaluation.Periods);
WriteLine(" Months");

namespace BusinessManagement
{
    static class LoanApplicant
    {
        public static int AccountNumber = 402_924_759;
        public static string FullName = "Joseph Nyate";
    }
}

namespace Information
{
    static class Evaluation
    {
        public static double LoanAmount = 2460;
        public static double InterestRate = 14.65; // %
        public static double Periods = 42d;
    }
}

As another option, in the top section of the code, type using static followed by the name of the namespace, a period, and the name of the class. Then, in the code, directly access any of the members of the static class. Here is an example:

using static System.Console;

using static Information.Evaluation;

WriteLine("Loan Application");
Write("Account #: ");
WriteLine(LoanApplicant.AccountNumber);
Write("Applicant Name: ");
WriteLine(LoanApplicant.FullName);
Write("Loan Amount: ");
WriteLine(LoanAmount);
Write("Interest Rate: ");
Write(InterestRate);
WriteLine("%");
Write("Perdiods: ");
Write(Periods);
WriteLine(" Months");

namespace BusinessManagement
{
    static class LoanApplicant
    {
        public static int AccountNumber = 402_924_759;
        public static string FullName = "Joseph Nyate";
    }
}

namespace Information
{
    static class Evaluation
    {
        public static double LoanAmount = 2460;
        public static double InterestRate = 14.65; // %
        public static double Periods = 42d;
    }
}

this Object

Introduction

If a class contains fields and methods, the (non-static) field members are automatically available to all method(s) of the class, even fields that are private. When working inside a class, such as accessing a field or a method of the class from another member of the same class, to let you indicate that you are referring to the class or to a member of the same class, the C# language provides a special object named this (in C++, it is called a pointer). Then add the period operator.

Accessing a Member of this Class

While working from within a class, to access one of its non-static member, you can type this followed by a period and the desired member. Here are examples:

public class Circle
{
    private double radius;

    public readonly double PI = 3.14159;

    public double CalculateDiameter()
    {
        return this.radius * 2;
    }

    public double CalculateCircumference()
    {
        return this.CalculateDiameter() * this.PI;
    }

    public double CalculateArea()
    {
        return this.radius * this.radius * this.PI;
    }
}

Because the this keyword indicates that you are using a member from within the class, a method can use a parameter that has the same name as a member of the class and, by using the this keyword, you wouold not have any name conflict. Here is an example:

public class Circle
{
    private double radius;

    public readonly double PI = 3.14159;

    public Circle(double radius)
    {
        // In "this.radius", the radius is the one in the class
        // In "radius", the radius is the parameter of the method
        this.radius = radius;
    }
}

As you might have realized from the above code and from previous lessons, the this keyword is mostly optional. Other than that, the public member can still be accessed outside the class.

Characteristics of this Object

When using this, you can access any member of a class within any method or property of the same class. There are rules you must observe when using this:

this Method Returns an Object of its Class

A method of a class can be made to return an object of its class. We saw this feature in a previous section. An alternative is to return the this object. Here is an example:

public class Chemistry
{
    public string Element;
    public string Symbol;
    public int AtomicNumber;
    public double AtomicWeight;

    public Chemistry Initialize()
    {
        Symbol = "N";
        AtomicNumber = 7;
        Element = "Nitrogen";
        AtomicWeight = 14.007;

        return this;
    }
}

The Main Function of an Application

The Main Entry-Point of an Application

When you have created and distributed an application, when people execute your application, the compiler needs to know where the execution of an application starts. In many languages such as F# and Pascal, the compiler proceeds from the top section or the first line of a file to the next, down to the end of the file. Some other languages such as C-based languages (C, C++, Java, C#, etc) and others (such as Visual Basic) must indicate to the compiler where to start executing the application. Those languages use a special function or method with a unique name as the starting point. That method is considered the entry-point of the application.

When you create a program in C#, that is, a program that will execute as a computer application, you must create a(t least one) class. In that class, you must include a static method named Main. Here is an example:

public class Exercise
{
    static void Main()
    {
    }
}

In the class that contains the Main() method, you can create other methods and you can create fields as necessary. To access the members of that class from the Main() method, you have two options.

You can create regular members in the class that contains the Main() method. If you want to access one of those members in the Main() method, you must declare a variable of the class and then access the member from that variable. That's how we have proceeded so far. Here are examples:

using static System.Console;

public class Vaccination
{
    string Interest = "Preventable Diseases";

    void Introduce()
    {
        WriteLine("A vaccination is a type of injected medication that mimics a person's immune system to simulate a pathogen. " +
		  "The end goal is to create a situation of immunity.");
    }

    string SpecifyOccurrence() => "A vaccination must be regulated by a government.";

    static void Main()
    {
        WriteLine("Department of Health");
        WriteLine("--------------------------------------------------");

        Vaccination injection = new Vaccination();

        WriteLine(injection.Interest);
        injection.Introduce();
        WriteLine("--------------------------------------------------");
        WriteLine(injection.SpecifyOccurrence());
        WriteLine("==================================================");
    }
}

If you want to directly access a member of that class in the Main() method, you must create that member as static. Here are examples:

using static System.Console;

public class Vaccination
{
    string Interest = "Preventable Diseases";

    void Introduce()
    {
        WriteLine("A vaccination is a type of injected medication that mimics a person's immune system to simulate a pathogen. " +
		  The end goal is to create a situation of immunity.");
    }

    string SpecifyOccurrence() => "A vaccination must be regulated by a government.";

    static string vaccinationName = "Quinimax Injection";

    static void DefineVeccination()
    {
        WriteLine("Quinimax Injection is a type of vaccination used to fight malaria, varicose, and other types of preventable deseases.");
    }

    static void Main()
    {
        WriteLine("Department of Health");
        WriteLine("--------------------------------------------------");

        Vaccination injection = new Vaccination();

        WriteLine(injection.Interest);
        injection.Introduce();
        WriteLine(injection.SpecifyOccurrence());
        WriteLine("==================================================");

        WriteLine("--------------------------------------------------");
        WriteLine("Vaccination Name: {0}", vaccinationName);

        DefineVeccination();
        WriteLine("==================================================");
    }
}

Main is Static

The Main() function or method is static. Therefore, when creating it, start it with the static keyword. Here is an example:

namespace ApplicationProgramming
{
    class Program
    {
        static void Main()
        {
            
        }
    }
}

As we have seen so far, the class that contains the Main() function is not static, but you can make it static if you want. If the class of the Main() function is not static, one of the ways you can use its class in the body of the Main() function is to declare a variable for it. You can then access the members of that class using the object of the class.

Main Can Return a Value

The default implementation of the Main() method is of type void. That's how we have used it so far. Here is an example:

public class Program
{
    static void Main()
    {
    }
}

As an alternative, you can implement the Main() method to return an integer. The rule is the same as for any method of type int. The Main() method can return any valid natural number. Here is an example:

public class Program

    static int Main()
    {

        return 244006;
    }
}

If you are using Microsoft Visual Studio, to create a Main() method using skeleton code, right-click the section where you want to add it and click Insert Snippet... Double-click Visual C#:

The Access of the Main Function

Like any regular method, the Main() function can use an access level. Normally, any of them will do: private, public, or internal; but most of the time, you should make it public. Here is an example:

public class Program
{
    public static void Main()
    {
    }
}

Class Nesting

Introduction

A class can be created inside of another class. A class created inside of another is referred to as nested.

Nesting a Class

To nest a class, click inside an existing class and type the necessary code for the new class, starting with the class keyword followed by a name and {}. If you are using Microsoft Visual Studio, select the whole class. Right-click the selection and click Surround With... In the list, double-click class. Here is an example of a class called Inside that is nested in a class called Outside:

public class Outside
{
    public class Inside
    {
    }
}

In the same way, you can nest as many classes as you wish in another class and you can nest as many classes as you want inside of other nested classes if you judge it necessary. Just as you would manage any other class, you exercise control a nested class. For example, you can create all necessary fields and/or methods in the nested class or in the nesting class. When you create one class inside of another, there is no special programmatic relationship between both classes: just because a class is nested does not mean that the nested class has immediate access to the members of the nesting class. They are two different classes and they can be used separately.

Accessing a Nested Class

The name of a nested class is not "visible" outside of the nesting class. To access a nested class outside of the nesting class, you must qualify the name of the nested class anywhere you want to use it. For example, if you want to declare an Inside variable somewhere in the program but outside of Outside, you must qualify its name. Here is an example:

public class Outside
{
    public class Inside
    {
    	public Inside()
	{
	    System.Console.WriteLine(" -= Inside =-");
	}
    }

    public Outside()
    {
	System.Console.WriteLine(" =- Outside -=");
    }
}

public class Exercise
{
    static int Main()
    {
    	Outside recto = new Outside();
	Outside.Inside ins = new Outside.Inside();

    	return 0;
    }
}

This would produce:

=- Outside -=
 -= Inside =-

Because there is no programmatically privileged relationship between a nested class and its "container" class, if you want to access the nested class in the nesting class, you can use its static members. In other words, if you want, you can create static members (fields and/or methods) of the nested class you want to access in the nesting class. Here is an example:

using static System.Console;

public class Outside
{
    public class Inside
    {
	public static string InMessage;

	public Inside()
	{
	    WriteLine(" -= Insider =-");
	    inMessage = "Sitting inside while it's raining";
	}

	public static void Show()
	{
	    WriteLine("Show me the wonderful world of C# Programming");
	}
    }

    public Outside()
    {
	Console.WriteLine(" =- The Parent -=");
    }

    public void Display()
    {
	WriteLine(Inside.InMessage);
	Inside.Show();
    }
}

class Exercise
{
    static void Main()
    {
	Outside recto = new Outside();
	Outside.Inside ins = new Outside.Inside();

	Recto.Display();
    }
}

In the same way, if you want to access the nesting class in the nested class, you can go through the static members of the nesting class. To do this, you can make static all members of the nesting class that you want to access in the nested class. Here is an example:

using static System.Console;

public class Outside
{
    public class Inside
    {
	public static string InMessage;

	public Inside()
	{
	    WriteLine(" -= Insider =-");
	    InMessage = "Sitting inside while it's raining";
	}

	public static void Show()
	{
	    WriteLine("Show me the wonderful world of C# Programming");
	}

	public void FieldFromOutside()
	{
	    WriteLine(Outside.OutMessage);
	}
    }

    private static string OutMessage;

    public Outside()
    {
	WriteLine(" =- The Parent -=");
	OutMessage = "Standing outside! It's cold and raining!!";
    }

    public void Display()
    {
	WriteLine(Inside.InMessage);
	Inside.Show();
    }
}

public class Exercise
{
    static void Main()
    {
	Outside recto = new Outside();
	Outside.Inside Ins = new Outside.Inside();

	Recto.Display();
	WriteLine();
	Ins.FieldFromOutside();

	return 1_000;
    }
}

This would produce:

=- The Parent -=
 -= Insider =-
Sitting inside while it's raining
Show me the wonderful world of C# Programming

Standing outside! It's cold and raining!!

Instead of static members, if you want to access members of a nested class in the nesting class, you can first declare a variable of the nested class in the nesting class. In the same way, if you want to access members of a nesting class in the nested class, you can first declare a variable of the nesting class in the nested class. Here is an example:

using static System.Console;

public class Outside
{
    // A member of the nesting class
    private string OutMessage;

    // The nested class
    public class Inside
    {
	// A field in the nested class
	public string InMessage;

	// A constructor of the nested class
	public Inside()
	{
	    WriteLine(" -= Insider =-");
	    this.InMessage = "Sitting inside while it's raining";
	}

	// A method of the nested class
	public void Show()
	{
	    // Declare a variable to access the nesting class
	    Outside outsider = new Outside();
	    WriteLine(outsider.OutMessage);
	}
    } // End of the nested class

    // A constructor of the nesting class
    public Outside()
    {
	this.OutMessage = "Standing outside! It's cold and raining!!";

	WriteLine(" =- The Parent -=");
    }

    // A method of the nesting class
    public void Display()
    {
	WriteLine(insider.InMessage);
    }

    // Declare a variable to access the nested class
    Inside insider = new Inside();
}

public class Exercise
{
    static int Main()
    {
	Outside recto = new Outside();
	Outside.Inside Ins = new Outside.Inside();

	Ins.Show();
	Recto.Display();
	return 0;
    }
}

This would produce:

-= Insider =-
 =- The Parent -=
 -= Insider =-
 -= Insider =-
 =- The Parent -=
Standing outside! It's cold and raining!!
Sitting inside while it's raining

Previous Copyright © 2001-2023, C# Key Saturday 29 April 2023, 23:54 Next