Static Fields

Introduction

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.

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

public class Exercise
{
    public void Create()
    {
        Chemistry elm = new Chemistry()
        {
            Symbol = "Be",
            AtomicNumber = 4,
            Element = "Beryllium",
            AtomicWeight = 9.0121831
        };

        Chemistry chem = new Chemistry()
        {
            Symbol = "B",
            AtomicNumber = 5,
            Element = "Boron",
            AtomicWeight = 10.81
        };
    }

    static void Main()
    {
        Exercise exo = new Exercise();
        exo.Create();
    }
}

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 of 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 called static.

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, or internal). 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.

Notice 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.

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 System;

namespace AltairRealtors2
{
    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;
            
            Console.WriteLine("==//== Altair Realtors ==//==");
            Console.WriteLine("--------------------------------");
            Console.Write("Number of Bedrooms:   ");
            Console.WriteLine(Residence.Bedrooms);
            Console.Write("Number of Bathrooms:  ");
            Console.WriteLine(Residence.Bathrooms);
            Console.Write("Construction Status:  ");
            Console.WriteLine(ConstructionStatus);
            Console.Write("Market Value:         $");
            Console.WriteLine(MarketValue);
            Console.WriteLine("================================"); }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Residence res = new Residence();

            res.Present();
        }
    }
}

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

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:

using System;

namespace AltairRealtors2
{
    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;

        }
    }
}

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:

using System.Windows.Forms;

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 member. Here are examples:

using System.Windows.Forms;

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:

using System;

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 for 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 for 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()
    {
    }
}

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:

using System;

public class Person
{
    public string firstName;
    public string lastName;

    static Person()
    {
    }

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

public class Exercise
{
    public static void Main()
    {
        Person pers = new Person("Gertrude", "Monay");
    }
}

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:

namespace BusinessManagement
{
    public class Exercise
    {
        static void Main()
        {
            System.Console.WriteLine("Loan Application");
            System.Console.Write("Account #: ");
            System.Console.WriteLine(LoanApplicant.AccountNumber);
            System.Console.Write("Applicant Name: ");
            System.Console.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 in this and the previous lesson, 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:

namespace BusinessManagement
{
    public class Exercise
    {
        static void Main()
        {
            System.Console.WriteLine("Loan Application");
            System.Console.Write("Account #: ");
            System.Console.WriteLine(LoanApplicant.AccountNumber);
            System.Console.Write("Applicant Name: ");
            System.Console.WriteLine(LoanApplicant.FullName);
            System.Console.Write("Loan Amount: ");
            System.Console.WriteLine(Information.Evaluation.LoanAmount);
            System.Console.Write("Interest Rate: ");
            System.Console.Write(Information.Evaluation.InterestRate);
            System.Console.WriteLine("%");
            System.Console.Write("Perdiods: ");
            System.Console.Write(Information.Evaluation.Periods);
            System.Console.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:

namespace BusinessManagement
{
    using Information;

    public class Exercise
    {
        static void Main()
        {
            System.Console.WriteLine("Loan Application");
            System.Console.Write("Account #: ");
            System.Console.WriteLine(LoanApplicant.AccountNumber);
            System.Console.Write("Applicant Name: ");
            System.Console.WriteLine(LoanApplicant.FullName);
            System.Console.Write("Loan Amount: ");
            System.Console.WriteLine(Evaluation.LoanAmount);
            System.Console.Write("Interest Rate: ");
            System.Console.Write(Evaluation.InterestRate);
            System.Console.WriteLine("%");
            System.Console.Write("Perdiods: ");
            System.Console.Write(Evaluation.Periods);
            System.Console.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:

namespace BusinessManagement
{
    using static Information.Evaluation;

    public class Exercise
    {
        static void Main()
        {
            System.Console.WriteLine("Loan Application");
            System.Console.Write("Account #: ");
            System.Console.WriteLine(LoanApplicant.AccountNumber);
            System.Console.Write("Applicant Name: ");
            System.Console.WriteLine(LoanApplicant.FullName);
            System.Console.Write("Loan Amount: ");
            System.Console.WriteLine(LoanAmount);
            System.Console.Write("Interest Rate: ");
            System.Console.Write(InterestRate);
            System.Console.WriteLine("%");
            System.Console.Write("Perdiods: ");
            System.Console.Write(Periods);
            System.Console.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;
    }
}

Console is a Static Class

As we have seen so far, to display something a in a DOS window, you can use the Console class defined in the System namespace. Actually, Console is a static class. As such, to use it, in the top section of your code, you can write using static System.Console;. Then, in your code, directly access any of its members. Here is an example:

using static System.Console;
using static Information.Evaluation;

namespace BusinessManagement
{
    
    public class Exercise
    {
        static void Main()
        {
            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 long 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. When and 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:

lass 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:

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

using System.Windows.Forms;

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

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 language use a special method with a unique name as the starting point. That method is considered the entry-point of the application.

When you create an application in C#, that is, an application 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. 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 with the static keywork. 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.

ApplicationPractical Learning: Using the Static Main() Function

  1. Start Microsoft Visual Studio
  2. On the Visual Studio 2019 dialog box, click Create a New Project (if Microsoft Visual Studio was already opened, on the main menu, click File -> New -> Project...)
  3. In the list of projects templates of the Create a New Project dialog box, click Console App (.NET Framework)
  4. Click Next
  5. Change the project Name to GeorgetownDryCleaningServices3
  6. Click Create
  7. In the Solution Explorer, right-click Program.cs and click Rename
  8. Type CustomerOrder (to get CustomerOrder.cs) and press Enter
  9. Read the message box and click Yes
  10. Change the class as follows:
    using System;
    
    namespace GeorgetownDryCleaningServices3
    {
        class CustomerOrder
        {
            readonly double priceOneShirt = 1.2;
            readonly double priceAPairOfPants = 2.3;
            readonly double priceOneDress = 3.5;
            readonly double discountRate = 0.125; // 12.50%
            readonly double taxRate = 6.15;  // 6.15%
    
            readonly string customerName = "Jason Becker",
                   homePhone = "(571) 397-5940";
            readonly int numberOfShirts = 5,
                   numberOfPants = 2,
                   numberOfDresses = 3;
            int totalNumberOfItems;
            double subTotalShirts, subTotalPants, subTotalDresses;
            double discountAmount, totalOrder, netPrice;
            double amountTended;
            readonly int orderMonth = 10, orderDay = 15, orderYear = 2020;
    
            private int AddThree(int a, int b, int c)
            {
                return a + b + c;
            }
    
            private double AddThree(double a, double b, double c)
            {
                return a + b + c;
            }
    
            private double MultiplyTwo(double x, double y)
            {
                return x + y;
            }
    
            private double CalculateTaxAmount()
            {
                return totalOrder * taxRate / 100;
            }
    
            private double CalculateSalesTotal()
            {
                return netPrice + CalculateTaxAmount();
            }
    
            private double CalculateDifference()
            {
                return amountTended - CalculateSalesTotal();
            }
            public void PresentOrder()
            {
                totalNumberOfItems = AddThree(numberOfShirts, numberOfPants, numberOfDresses);
                subTotalShirts = MultiplyTwo(priceOneShirt, numberOfShirts);
                subTotalPants = MultiplyTwo(priceAPairOfPants, numberOfPants);
                subTotalDresses = MultiplyTwo(numberOfDresses, priceOneDress);
                totalOrder = AddThree(subTotalShirts, subTotalPants, subTotalDresses);
                discountAmount = MultiplyTwo(totalOrder, discountRate);
                netPrice = totalOrder - discountAmount;
                
                amountTended = 20;
    
                Console.WriteLine("-/- Georgetown Cleaning Services -/-");
                Console.WriteLine("====================================");
                Console.Write("Customer:   ");
                Console.WriteLine(customerName);
                Console.Write("Home Phone: ");
                Console.WriteLine(homePhone);
                Console.Write("Order Date: ");
                Console.Write(orderMonth);
                Console.Write("/");
                Console.Write(orderDay);
                Console.Write('/');
                Console.WriteLine(orderYear);
                Console.WriteLine("------------------------------------");
                Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
                Console.WriteLine("------------------------------------");
                Console.Write("Shirts      ");
                Console.Write(numberOfShirts);
                Console.Write("     ");
                Console.Write(priceOneShirt.ToString("F"));
                Console.Write("     ");
                Console.WriteLine(subTotalShirts.ToString("F"));
                Console.Write("Pants       ");
                Console.Write(numberOfPants);
                Console.Write("     ");
                Console.Write(priceAPairOfPants.ToString("F"));
                Console.Write("     ");
                Console.WriteLine(subTotalPants.ToString("F"));
                Console.Write("Dresses     ");
                Console.Write(numberOfDresses);
                Console.Write("     ");
                Console.Write(priceOneDress.ToString("F"));
                Console.Write("     ");
                Console.WriteLine(subTotalDresses.ToString("F"));
                Console.WriteLine("------------------------------------");
                Console.Write("Number of Items: ");
                Console.WriteLine(totalNumberOfItems);
                Console.Write("Total Order:     ");
                Console.WriteLine(totalOrder.ToString("F"));
                Console.Write("Discount Rate:   ");
                Console.Write(discountRate * 100);
                Console.WriteLine("%");
                Console.Write("Discount Amount: ");
                Console.WriteLine(discountAmount.ToString("F"));
                Console.Write("After Discount:  ");
                Console.WriteLine(netPrice.ToString("F"));
                Console.Write("Tax Rate:        ");
                Console.Write(taxRate);
                Console.WriteLine("%");
                Console.Write("Tax Amount:      ");
                Console.WriteLine(CalculateTaxAmount().ToString("F"));
                Console.Write("Net Price:       ");
                Console.WriteLine(CalculateSalesTotal().ToString("F"));
                Console.WriteLine("====================================");
                Console.Write("Amount Tended:   ");
                Console.WriteLine(amountTended);
                Console.Write("Difference:      ");
                Console.WriteLine(CalculateDifference().ToString("F"));
                Console.WriteLine("====================================");
            }
    
            static void Main()
            {
                CustomerOrder co = new CustomerOrder();
    
                co.PresentOrder();
            }
        }
    }
  11. To execute, on the main menu, click Debug -> Start Without Debugging:
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   Jason Becker
    Home Phone: (571) 397-5940
    Order Date: 10/15/2020
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     1.20     6.20
    Pants       2     2.30     4.30
    Dresses     3     3.50     6.50
    ------------------------------------
    Number of Items: 10
    Total Order:     17.00
    Discount Rate:   12.5%
    Discount Amount: 17.13
    After Discount:  -0.13
    Tax Rate:        6.15%
    Tax Amount:      1.05
    Net Price:       0.92
    ====================================
    Amount Tended:   20
    Difference:      19.08
    ====================================
    Press any key to continue . . .
  12. Press Enter to close the DOS windows and return to your programming environment

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 so can you exercise control on 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:

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

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

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

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

    public void Display()
    {
		System.Console.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:

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

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

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

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

    private static string OutMessage;

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

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

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

		Recto.Display();
		Console.WriteLine();
		Ins.FieldFromOutside();
		return 0;
    }
}

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 System;

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()
		{
		    System.Console.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();
		    System.Console.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!!";

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

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

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

public class Exercise
{
    static void 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

ApplicationPractical Learning: Ending the Lesson


Previous Copyright © 2001-2021, C# Key Next