Home

Introduction to Built-In Classes

The Object Class

Introduction

C# was clearly created to improve on C++ and possibly offer a new alternative. To achieve this goal, Microsoft created a huge library to accompany the language. The .NET Framework is a huge library made of various classes and constants you can directly use in your C# application without necessarily explicitly loading an external library. To start, this main library of C# provides a class called object.

As you may have realized by now, every variable or function in C# (as in Java) must belong to a class, unlike C/C++ where you can have global variables or functions. Therefore, you always have to create at least one class for your application. As such, when you create a class, it automatically inherits its primary characteristics from the parent of all classes: object.

ApplicationApplication: Introducing Ancestor Classes

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click FILE -> New -> Project...
  3. In the middle list, click Empty Project
  4. Change the Name to UtilityCompany1 and press Enter
  5. To create a new class, in the Class View, right-click UtilityCompany1 -> Add -> Class...
  6. Set the Name to Customer and click Add
  7. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace UtilityCompany1
    {
        public class Customer
        {
            private long acnt;
            private string fn;
    
            public Customer(string number = "", string name = "")
            {
                acnt = number;
                fn = name;
            }
        }
    }
  8. In the document, right-click acnt, position the mouse on Refactor, and click Encapsulate Field...
  9. In the Encapsulate Field dialog box, change the name to AccountNumber
     
    Encapsulate Field
  10. Click OK
  11. In the Preview Reference Changes dialog box, check the code and click Apply
  12. In the document, right-click fn -> Refactor -> Encapsulate Field...
  13. In the Encapsulate Field dialog box, change the name to FullName
  14. Click OK
  15. In the Preview Reference Changes dialog box, check the code and click Apply
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace UtilityCompany1
    {
        public class Customer
        {
            private string acnt;
            private string fn;
    
            public Customer(string number = "", string name = "")
            {
                acnt = number;
                fn = name;
            }
    
            public string AccountNumber
            {
                get { return acnt; }
                set { acnt = value; }
            }
    
            public string FullName
            {
                get { return fn; }
                set { fn = value; }
            }
        }
    }
  16. To create a new file, in the Solution Explorer, right-click UtilityCompany1 -> Add -> New Item...
  17. In the middle list, click Code File...
  18. Change the Name to AccountProcessing and click Add
  19. In the empty document, type the following:
    using System;
    using UtilityCompany1;
    
    public class ProcessingAccount
    {
        public Customer Register()
        {
            string accountNumber;
            string custName;
    
            Response.Write("============================");
            Response.Write("Utility Bill");
            Response.Write("----------------------------");
            Response.Write("Enter Customer Information");
            Response.Write("Account Number: ");
            accountNumber = Console.ReadLine();
            Response.Write("Customer Name:  ");
            custName = Console.ReadLine();
    
            Customer cust = new Customer(accountNumber, custName);
            return cust;
        }
    
        public void CreateUtilityBill(Customer custInfo)
        {
            Response.Write("============================");
            Response.Write("Utility Bill");
            Response.Write("----------------------------");
            Response.Write("Customer Name:  {0}", custInfo.AccountNumber);
            Response.Write("Account Number: {0}", custInfo.FullName);
            Response.Write("============================");
        }
    
        public static int Main()
        {
            Customer cust = null; // new Customer();
            ProcessingAccount pa = new ProcessingAccount();
    
            Response.Write("Utility Company");
            cust = pa.Register();
    
            Console.Clear();
    
            pa.CreateUtilityBill(cust);
            System.Console.ReadKey();
    
            return 0;
        }
    }
  20. To execute the application, on the main menu, click DEBUG -> Start Debugging
  21. When requested, enter the account number as 28-614007-59 and press Enter
  22. Enter the name as George Sandt and press Enter

Equality of Two Class Variables

When you declare and initialize two variables, one of the operations you may want to subsequently perform is to compare their value. To support this operation, the Object class provides its children with a method called Equals. The Equals() method comes in two versions. The first has the following syntax:

public virtual bool Equals(object obj);

This version allows you to call the Equals() method on a declared variable and pass the other variable as argument. Here is an example:

using System;

class BookCollection
{
    static void Main()
    {
	// First book
	int numberOfPages1 = 422;
	// Second book
	int numberOfPages2 = 858;
	// Third book
	int numberOfPages3 = 422;

	if( numberOfPages1.Equals(numberOfPages2) == true )
      Response.Write("The first and the second books have the same number of pages");
	else
      Response.Write("The first and the second books have different number of pages");
			
	if( numberOfPages1.Equals(numberOfPages3) == true )
      Response.Write("The first and the third books have the same number of pages");
	else
      Response.Write("The first and the third books have different number of pages");
    }
}

This would produce:

The first and the second books have different number of pages
The first and the third books have the same number of pages

The first version of the Object.Equals method is declared as virtual, which means you can override it if you create your own class. The second version of the Object.Equals() method is:

public static bool Equals(object obj2, object obj2);

As a static method, to use it, you can pass the variables of the two classes whose values you want to compare.

In both cases, if the values of the variables are similar, the Equals() method returns true. If they are different, the method returns false. If you are using the Equals() method to compare the variables of two primitive types, the comparison should be straight forward. If you want to use this methods on variables declared from your own class, you should provide your own implementation of this method.

ApplicationApplication: Implementing Equality

  1. Access the Customer.cs file
  2. To create your own implementation of the Equals() method, change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace UtilityCompany1
    {
        public class Customer
        {
            private string acnt;
            private string fn;
    
            public Customer(string number = "", string name = "")
            {
                acnt = number;
                fn = name;
            }
    
            public string AccountNumber
            {
                get { return acnt; }
                set { acnt = value; }
            }
    
            public string FullName
            {
                get { return fn; }
                set { fn = value; }
            }
    
            public override bool Equals(object obj)
            {
                Customer cust = (Customer)obj;
    
                if( (acnt == cust.acnt) &&
                    (fn == cust.fn) )
                    return true;
    
                return false;
            }
        }
    }
  3. Access the AccountProcessing.cs file and change it as follows:
    using System;
    using UtilityCompany1;
    
    public class ProcessingAccount
    {
        . . . No Change
    
        public static int Main()
        {
            var first = new Customer("72-975947-64", "James Barans");
            var second = new Customer("50-315759-95", "Paul Motto");
            var third = new Customer("72-975947-64", "James Barans");
    
            if (first.Equals(second))
            {
                Response.Write("The first and the second records ");
                Response.Write("represent the same customer.");
            }
            else
                Response.Write("The first and the second records are different.");
    
            if (first.Equals(third))
            {
                Response.Write("The first and the third records ");
                Response.Write("represent the same customer");
            }
            else
                Response.Write("The first and the third records are different.");
            
            System.Console.ReadKey();
            return 0;
        }
    }
  4. To execute the application, on the main menu, click DEBUG -> Start Debugging. This would produce:
    The first and the second records are different.
    The first and the third records represent the same customer
  5. Close the DOS window

Stringing an Object

In previous lessons, we learned that, to convert the value of a variable declared from a primitive type to a string, you could call the ToString() function. Here is an example:

using System;

class BookCollection
{
    static int Main()
    {
	int numberOfPages = 422;
	
        Response.Write("Number of Pages: {0}", numberOfPages.ToString());
	return 0;
    }
}

In many programming languages such as C++, programmers usually have to overload an (extractor) operator to display the value(s) of class' variable to the screen. The Object class provides an alternative to this somewhat complicated solution, through the ToString() method. It syntax is:

public virtual string ToString();

Although the Object class provides this method as non abstract, its implemented version is more useful if you use a primitive type such as int, double and their variances or a string variable. The best way to rely on it consists of overriding it in your own class if you desired to use its role.

ApplicationApplication: Converting to String

  1. Access the Customer.cs file
  2. To implement and use a ToString() method, change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace UtilityCompany1
    {
        public class Customer
        {
            private string acnt;
            private string fn;
    
            public Customer(string number = "", string name = "")
            {
                acnt = number;
                fn = name;
            }
    
            public string AccountNumber
            {
                get { return acnt; }
                set { acnt = value; }
            }
    
            public string FullName
            {
                get { return fn; }
                set { fn = value; }
            }
    
            public override bool Equals(object obj)
            {
                Customer cust = (Customer)obj;
    
                if( (acnt == cust.acnt) &&
                    (fn == cust.fn) )
                    return true;
    
                return false;
            }
    
            public override string ToString()
            {
                return "Customer Name:  " + acnt +
                       "\nAccount Number: " + fn;
            }
        }
    }
  3. Access the AccountProcessing.cs file and change it as follows:
    using System;
    using UtilityCompany1;
    
    public class ProcessingAccount
    {
        public Customer Register()
        {
            string accountNumber;
            string custName;
    
            Response.Write("============================");
            Response.Write("Utility Bill");
            Response.Write("----------------------------");
            Response.Write("Enter Customer Information");
            Response.Write("Account Number: ");
            accountNumber = Console.ReadLine();
            Response.Write("Customer Name:  ");
            custName = Console.ReadLine();
    
            Customer cust = new Customer(accountNumber, custName);
            return cust;
        }
    
        public void CreateUtilityBill(Customer custInfo)
        {
            Response.Write("============================");
            Response.Write("Utility Bill");
            Response.Write("----------------------------");
            Response.Write(custInfo);
            Response.Write("============================");
        }
    
        public static int Main()
        {
            Customer cust = null; // new Customer();
            ProcessingAccount pa = new ProcessingAccount();
    
            Response.Write("Utility Company");
            cust = pa.Register();
    
            Console.Clear();
    
            pa.CreateUtilityBill(cust);
            System.Console.ReadKey();
            
            return 0;
        }
    }
  4. To execute the application, on the main menu, click DEBUG -> Start Debugging
  5. When requested, enter the account number as 44-204814-18 and press Enter
  6. Enter the name as William Bohden and press Enter
  7. Close the DOS window

Boxing and Un-Boxing

When we study inheritance, we will learn that all data types used in a C# program are "based on" an object called object. As introduced earlier, you can use this data type to declare a variable that would hold any type of value. Because this is some type of a "universal" data type, it can also be initialized with any value. Here are examples:

using System;

class Exercise
{
	static void Main()
	{
		object Number = 244;
		object Thing  = "Professor Kabba";

		Response.Write(Number);
		Response.Write(Thing);
	}
}

This would produce:

244
Professor Kabba

As you can see, when an object variable is initialized, the compiler finds out the type of value that was assigned to it. This is referred to as boxing. This mechanism is transparently done in C# (and in Visual Basic but not in Visual C++ 2003 (it is possible that something will be done in the next version, or not)).

If you declare a variable using a primitive data type (int, float, double, etc), at one time, you may be interested in converting the value of that variable into an object. Here is an example:

using System;

class Exercise
{
    static int Main()
    {
	int Number = 244;
	object Thing  = Number;

	Response.Write(Number);
	Response.Write(Thing);
	return 0;
    }
}

This would produce:

244
244

This operation is referred to as unboxing. As you can see, this operation is performed transparently (Visual C++ 2003 doesn't do it transparently).

Boxing and unboxing make C# a very flexible and wonderful language (if you misuse it, of course it can be dangerous).

Finalizing a Variable

While a constructor, created for each class, is used to instantiate a class. The object class provides the Finalize() method as a type of destructor.

Other Built-In Classes

The System namespace provides one of the largest definition of classes of the .NET Framework, but it doesn't contain everything. For example, when you start writing graphical user interface (GUI) applications, you will have to use other namespaces. The namespaces are contained in libraries called assemblies. The actual classes used in various applications are created and defined in these libraries. Before using a class, you must know the name of the assembly in which it is defined. You must also know the name of its namespace. These three pieces of information, the name of the class, the namespace in which it is defined, and the name of the assembly in which the namespace is contained, are very important. Because there are so many classes, namespaces, and libraries, the MSDN documentation is your best reference. We can only mention a few, especially those that are relevant for the subjects we are reviewing.

The Convert class will be reviewed in Lesson 29.

Random Numbers

Introduction

Imagine you have a series of numbers, such these: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, and 20. Imagine you want to select one of these numbers, any of them. A number is referred to as random if it has been selected from a pool without a specific pattern to follow. For example, if you decide to select the value 17 from this list, if there was an exact reason that number was selected, then it is not considered random. In reality, it is difficult for a number to qualify as random. For this reason, most random numbers are referred to as pseudo-random.

ApplicationApplication: Introducing Random Numbers

  1. To create a new application, on the main menu, click FILE -> New -> Project...
  2. In the middle list, click Empty Project
  3. Change the Name to NationalBank6 and press Enter
  4. To create a new file, on the main menu, click PROJECT -> Add New Item...
  5. In the middle list, click Code File
  6. Change the Name of the file to Employee
  7. Click Add
  8. Complete the Employee.cs file as follows:
    public enum EmploymentStatus
    {
        FullTime,
        PartTime,
        Internship,
        Unknown
    }
    
    public class Employee
    {
        public string EmployeeNumber { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }
        public double HourlySalary { get; set; }
        public EmploymentStatus Status { get; set; }
    
        public Employee(string emplNbr = "000-000", string fName = "John",
                        string lName = "Doe")
        {
            EmployeeNumber = emplNbr;
            FirstName = fName;
            LastName = lName;
            Title = "";
            HourlySalary = 0.00D;
            Status = EmploymentStatus.Unknown;
        }
    }
  9. To create a new file, on the main menu, click PROJECT -> Add New Item...
  10. In the middle list, click Code File
  11. Change the Name of the file to Customer
  12. Click Add
  13. Complete the Customer.cs file as follows:
    public enum AccountType { Checking, Saving, Other }
    
    public class Customer
    {
        public string AccountNumber { get; set; }
        public string FullName { get; set; }
        public AccountType Type { get; set; }
        public double Balance { get; set; }
        public short PIN { get; set; }
    
        public Customer(string acnt = "000-000000-000",
                        string name = "John Doe",
                        AccountType category = AccountType.Other)
        {
            AccountNumber = acnt;
            FullName = name;
            Type = category;
            PIN = 0;
            Balance = 0.00D;
        }
    }
  14. To create a new file, in the Solution Explorer, right-click NationalBank6 -> Add -> New Item...
  15. In the middle list, make sure Code File is selected.
    Change the Name to Management and press Enter
  16. Complete the file as follows:
    using System;
    
    public class Management
    {  
        public static int Main()
        {
            return 0;
        }
    }

Getting a Random Number

To support the ability to create or choose a random number, the .NET Framework provides the Random class. To start, you can declare a variable of this class, using one of its two constructors. Here is an example that uses the default constructor:

using System;

class Program
{
    static int Main()
    {
        Random rndNumber = new Random();
       
        return 0;
    }
}

After creating the variable, you can start getting numbers from it. To do this, you call the Next() method, which is overloaded in three versions. One of the versions of this method takes no argument and its syntax is:

public virtual int Next();

This method generates a randomly selected integer between 0 and the MinValue value of the int data type. Here is an example:

using System;

class Program
{
    static int Main()
    {
        Random rndNumbers = new Random();
        int    rndNumber = rndNumbers.Next();

        Response.Write("Number: {0}", rndNumber);
       
        return 0;
    }
}

Here is an example of running the program:

Number: 1369872590
Press any key to continue . . .

In the same way, you can call this version of the Next() method repeatedly to get random. Here is an example:

using System;

class Program
{
    static int Main()
    {
        Random rndNumbers = new Random();
        int rndNumber = 0;

        for (int nbr = 1; nbr < 9; nbr++)
        {
            rndNumber = rndNumbers.Next();
            Response.Write("Number: {0}", rndNumber);
        }

        return 0;
    }
}

Here is an example of running the program:

Number: 1924504148
Number: 1257846191
Number: 424740120
Number: 1009211682
Number: 544356245
Number: 708951978
Number: 759684741
Number: 1325535324
Press any key to continue . . .

The Seed of a Random Number

Consider the following program:

using System;

class Program
{
    static int Main()
    {
        Random rndNumbers = new Random();
        int rndNumber = rndNumbers.Next();

        Response.Write("Number: {0}", rndNumber);

        return 0;
    }
}

Here is an example of running the program:

Number: 573991745
Press any key to continue . . .

Here is another example of running the same program:

Number: 334223329
Press any key to continue . . .

Notice that the numbers generated are different. When creating a program that repeatedly gets a series of random numbers, you may (or may not) want the Random class to generate the same number over and over again. A seed is a constant value that controls whether a random generation would produce the same result every time it occurs. For example, using a seed, you can impose it upon the Random class to generate the same number every time the Next() method is called. To support the ability to use a seed, the Random class is equipped with a second constructor whose syntax is:

public Random(int Seed);

Based on this, to specify a seed, when declaring a Random variable, pass a constant integer to the constructor. Here is an example:

using System;

class Program
{
    static int Main()
    {
        Random rndNumbers = new Random(20);
        int rndNumber = rndNumbers.Next();

        Response.Write("Number: {0}", rndNumber);

        return 0;
    }
}

Here is one example of running the program:

Number: 375271809
Press any key to continue . . .

Here is another example of running the same program:

Number: 375271809
Press any key to continue . . .

Notice that the numbers are the same. Consider this program also:

using System;

class Program
{
    static int Main()
    {
        Random rndNumbers = new Random(20);
        int rndNumber = 0;


        for (int nbr = 1; nbr < 5; nbr++)
        {
            rndNumber = rndNumbers.Next();
            Response.Write("Number: {0}", rndNumber);
        }

        return 0;
    }
}

Here is one example of running the program:

Number: 375271809
Number: 1472524622
Number: 1605850688
Number: 1776011503
Press any key to continue . . .

Here is another example of running the same program:

Number: 375271809
Number: 1472524622
Number: 1605850688
Number: 1776011503
Press any key to continue . . .

Notice that the sequences are the same. In both cases, this indicates that, if you specify a seed, the Random class would generate the same number or the same sequence of numbers.

ApplicationApplication: Getting a Random Number

  1. Change the Management.cs file as follows:
    using System;
    
    public class Management
    {
        private EmploymentStatus GetEmployeeStatus()
        {
            byte status = 0;
    
            Response.Write("Employment Status");
            Response.Write("1. Full-Time");
            Response.Write("2. Part-Time");
            Response.Write("3. Intern");
            Response.Write("Your Choice? ");
            status = byte.Parse(Console.ReadLine());
    
            if (status == 1)
                return EmploymentStatus.FullTime;
            else if (status == 2)
                return EmploymentStatus.PartTime;
            else if (status == 3)
                return EmploymentStatus.Internship;
            else
                return EmploymentStatus.Unknown;
        }
    
        private Employee HireEmployee()
        {
            Employee empl = new Employee();
            int position1, position2, position3, position4, position5, position6;
    
            Console.Title = "National Bank";
            Response.Write("===========================================");
            Response.Write("==-= National Bank =-==");
            Response.Write("To hire a new employee, enter the following information");
            Response.Write("-------------------------------------------");
            
            Random rndNumber = new Random();
            position1 = rndNumber.Next(9);
            position2 = rndNumber.Next(9);
            position3 = rndNumber.Next(9);
            position4 = rndNumber.Next(9);
            position5 = rndNumber.Next(9);
            position6 = rndNumber.Next(9);
    
            empl.EmployeeNumber = position1.ToString() + position2.ToString() + 
                                  position3.ToString() + "-" + position4.ToString() +
                                  position5.ToString() + position6.ToString();
            Response.Write("First Name:    ");
            empl.FirstName = Console.ReadLine();
            Response.Write("Last Name:     ");
            empl.LastName = Console.ReadLine();
            Response.Write("Title:         ");
            empl.Title = Console.ReadLine();
            Response.Write("Hourly Salary: ");
            empl.HourlySalary = double.Parse(Console.ReadLine());
            empl.Status = GetEmployeeStatus();
            Response.Write("===========================================");
    
            return empl;
        }
    
        private void ShowEmployeeRecord(Employee empl)
        {
            Response.Write("===========================================");
            Response.Write("==-= National Bank =-======================");
            Response.Write("    Employee Record");
            Response.Write("-------------------------------------------");
            Response.Write("Employee #:        {0}", empl.EmployeeNumber);
            Response.Write("First Name:        {0}", empl.FirstName);
            Response.Write("Last Name:         {0}", empl.LastName);
            Response.Write("Employee Title:    {0}", empl.Title);
            Response.Write("Hourly Salary:     {0}", empl.HourlySalary);
            Response.Write("Employment Status: {0}", empl.Status);
            Response.Write("===========================================");
        }
    
        private AccountType SpecifyAccountType()
        {
            byte type = 0;
    
            Response.Write("What type of account the customer wants to open");
            Response.Write("1 - Checking Account");
            Response.Write("2 - Savings Account");
            Response.Write("Enter account type: ");
            type = byte.Parse(Console.ReadLine());
    
            if (type == 1)
                return AccountType.Checking;
            else if (type == 2)
                return AccountType.Saving;
            else
                return AccountType.Other;
        }
    
        private Customer CreateNewAccount()
        {
            Customer client = new Customer();
            string pos1, pos2, pos3,
                   pos4, pos5, pos6, pos7, pos8, pos9,
                   pos10, pos11, pos12;
    
            Response.Write("===========================================");
            Response.Write("==-= National Bank =-======================");
            Response.Write("-------------------------------------------");
            Response.Write("Enter customer name: ");
            client.FullName = Console.ReadLine();
    
            Random rndNumber = new Random();
            pos1  = rndNumber.Next(9).ToString();
            pos2  = rndNumber.Next(9).ToString();
            pos3  = rndNumber.Next(9).ToString();
            pos4  = rndNumber.Next(9).ToString();
            pos5  = rndNumber.Next(9).ToString();
            pos6  = rndNumber.Next(9).ToString();
            pos7  = rndNumber.Next(9).ToString();
            pos8  = rndNumber.Next(9).ToString();
            pos9  = rndNumber.Next(9).ToString();
            pos10 = rndNumber.Next(9).ToString();
            pos11 = rndNumber.Next(9).ToString();
            pos12 = rndNumber.Next(9).ToString();
     
            client.AccountNumber = pos1.ToString() + pos2.ToString() + pos3.ToString() + "-" +
                                   pos4.ToString() + pos5.ToString() + pos6.ToString() +
                                   pos7.ToString() + pos8.ToString() + pos9.ToString() + "-" +
                                   pos10.ToString() + pos11.ToString() + pos12.ToString();
    
            client.Type = SpecifyAccountType();
            Response.Write("Ask the customer to enter a PIN: ");
            client.PIN = short.Parse(Console.ReadLine());
    
            return client;
        }
    
        public double Deposit()
        {
            double amount = 0;
    
            Response.Write("Amount to deposit: ");
            amount = double.Parse(Console.ReadLine());
    
            return amount;
        }
    
        public double Withdraw(Customer cust)
        {
            double amount = 0;
    
            Response.Write("Amount to withdraw: ");
            amount = double.Parse(Console.ReadLine());
    
            if (amount > cust.Balance)
            {
                Response.Write("You are not allowed to withdraw more money than your account has.");
                Console.ReadKey();
                return 0.00D;
            }
            else
                return amount;
        }
    
        private void ShowAccountInformation(Customer cust)
        {
            Response.Write("===========================================");
            Response.Write("==-= National Bank =-======================");
            Response.Write("Customer Account Information");
            Response.Write("-------------------------------------------");
            Response.Write("Account #:    {0}", cust.AccountNumber);
            Response.Write("Account Type: {0}", cust.Type);
            Response.Write("Full Name:    {0}", cust.FullName);
            Response.Write("PIN #:        {0}", cust.PIN);
            Response.Write("Balance:      {0:F}", cust.Balance);
            Response.Write("===========================================");
        }
    
        public static int Main()
        {
            double amount = 0;
            byte nextAction = 0;
            Employee clerk = null;
            Customer accountHolder = null;
            Management registration = new Management();
    
            Console.Title = "National Bank";
    
            clerk = registration.HireEmployee();
            Console.Clear();
            registration.ShowEmployeeRecord(clerk);
            Response.Write("Press Enter for next action");
            Console.ReadKey();
            Console.Clear();
    
            accountHolder = registration.CreateNewAccount();
            Response.Write("Enter the customer's initial deposit");
            accountHolder.Balance = registration.Deposit();
            Console.Clear();
    
            registration.ShowAccountInformation(accountHolder);
    
            do
            {
                Response.Write("What do you want to do now?");
                Response.Write("0 - Close the application");
                Response.Write("1 - Check account balance");
                Response.Write("2 - Make a deposit");
                Response.Write("3 - Withdraw money");
                Response.Write("4 - Transfer money from one account to another");
                Response.Write("Enter your choice: ");
                nextAction = byte.Parse(Console.ReadLine());
                Console.Clear();
    
                switch (nextAction)
                {
                    case 1:
                        Console.Clear();
                        registration.ShowAccountInformation(accountHolder);
                        Response.Write("Press Enter for next operation");
                        Console.ReadKey();
                        break;
    
                    case 2:
                        amount = registration.Deposit();
                        accountHolder.Balance += amount;
                        Console.Clear();
                        registration.ShowAccountInformation(accountHolder);
                        break;
    
                    case 3:
                        amount = registration.Withdraw(accountHolder);
                        accountHolder.Balance -= amount;
                        Console.Clear();
                        registration.ShowAccountInformation(accountHolder);
                        break;
    
                    case 4:
                        Response.Write("Operation not available: You have only one account with us");
                        break;
    
                    default:
                        return 0;
                }
    
                if ((nextAction < 1) || (nextAction > 4))
                    Response.Write("Invalid Action: Please enter a value between 1 and 4");
            } while ((nextAction >= 1) && (nextAction <= 4));
    
            Console.ReadKey();
            return 0;
        }
    }
  2. Press F5 to execute
  3. Forst the employee, type the first name as Amie and press Enter
  4. Type the last name as Downs and press Enter
  5. Type the Title as Branch Manager and press Enter
  6. Type the Hourly Salary as 38.85 and press Enter
  7. Type the Employment Status as 1 and press Enter
    ===========================================
    ==-= National Bank =-==
    To hire a new employee, enter the following information
    -------------------------------------------
    First Name:    Amie
    Last Name:     Downs
    Title:         Branch Manager
    Hourly Salary: 38.85
    Employment Status
    1. Full-Time
    2. Part-Time
    3. Intern
    Your Choice? 1
  8. Press Enter
    ===========================================
    ==-= National Bank =-======================
        Employee Record
    -------------------------------------------
    Employee #:        055-235
    First Name:        Amie
    Last Name:         Downs
    Employee Title:    Branch Manager
    Hourly Salary:     38.85
    Employment Status: FullTime
    ===========================================
    Press Enter for next action
  9. Press Enter to continue
  10. Type the Customer Name as Raymond Saltzman and press Enter
  11. Type the Account Type as 3 and press Enter
  12. Type the PIN as 5820 and press Enter
  13.  Type the Deposit Amount as 300 and press Enter
    ===========================================
    ==-= National Bank =-======================
    Customer Account Information
    -------------------------------------------
    Account #:    157-867445-432
    Account Type: Other
    Full Name:    Raymond Saltzman
    PIN #:        5820
    Balance:      300.00
    ===========================================
    What do you want to do now?
    0 - Close the application
    1 - Check account balance
    2 - Make a deposit
    3 - Withdraw money
    4 - Transfer money from one account to another
    Enter your choice:
  14. Type 0 to exit, close the DOS window, and return top your programming environment

Generating Random Numbers in a Range of Numbers

So far, we have been using any number that would fit an integer. In some assignments, you may want to restrict the range of numbers that can be extracted. Fortunately, the Random class allows this. Using the Random class, you can generate random positive numbers up to a maximum of your choice. To support this, the Random class is equipped with another version of the Next() method whose syntax is:

public virtual int Next(int maxValue);

The argument to pass to the method determines the highest integer that can be generated by the Next() method. The method returns an integer. Here is an example that generates random numbers from 0 to 20:

using System;

class Program
{
    static int Main()
    {
        Random rndNumbers = new Random();
        int rndNumber = 0;


        for (int nbr = 1; nbr < 9; nbr++)
        {
            rndNumber = rndNumbers.Next(20);
            Response.Write("Number: {0}", rndNumber);
        }

        return 0;
    }
}

Here is an example of running the program:

Number: 1
Number: 7
Number: 1
Number: 16
Number: 14
Number: 19
Number: 3
Number: 1
Press any key to continue . . .

The above version of the Next() method generates numbers starting at 0. If you want, you can specify the minimum and the maximum range of numbers that the Next() method must work with. To support this, the Random class is equipped with one more version of this method and that takes two arguments. Its syntax is:

public virtual int Next(int minValue, int maxValue);

The first argument specifies the lowest value that can come from the range. The second argument holds the highest value that the Next() method can generate. Therefore, the method would operate between both values. Here is an example that generates random numbers from 6 to 18:

using System;

class Program
{
    static int Main()
    {
        Random rndNumbers = new Random();
        int rndNumber = 0;


        for (int nbr = 1; nbr < 9; nbr++)
        {
            rndNumber = rndNumbers.Next(6, 18);
            Response.Write("Number: {0}", rndNumber);
        }

        return 0;
    }
}

Here is an example of running the program:

Number: 17
Number: 9
Number: 8
Number: 15
Number: 10
Number: 9
Number: 13
Number: 11
Press any key to continue . . .

Notice that the numbers are between 6 and 18.


Previous Copyright © 2008-2016, FunctionX Next