Fundamental Built-In Classes and Types

Overview

You will have to create some of the classes you need for your applications, but to assist you in working fast and efficiently, the .NET Framework provides a very rich collection of classes. A class is referred to as built-in if it is already available in the .NET Framework.

Introduction to the Object

The .NET library is a huge library made of various classes you can directly use in your C# applications. In the .NET Framework, an object is any type of value. To support objects, the .NET Framework provides a class named Object. To support objects, the C# language uses a data type named object. You can use it to declare a variable of any kind. After declaring the variable, Initialize with a value of your choice. Here are examples:

object employeeName = "Philippe Blayne";
object hourlySalary = 26.95;
object yearsOfExperience = 5;

To present the value to the console window, pass the name of the variable in the parentheses of Write() or WriteLine(). Here are examples:

using static System.Console;

object employeeName = "Philippe Blayne";
object hourlySalary = 26.95;
object yearsOfExperience = 5;

WriteLine("=//= Employee Record =//=");
Write("Employee Name: ");
WriteLine(employeeName);
Write("Hourly Salary: ");
WriteLine(hourlySalary);
Write("Length of Experience: ");
Write(yearsOfExperience);
WriteLine(" years");

This would produce:

=//= Employee Record =//=
Employee Name: Philippe Blayne
Hourly Salary: 26.95
Length of Experience: 5 years
Press any key to close this window . . .

You can also use object as a parameter to a method or function. Here is an example:

void PresentEmployeeSummary(object something)
{

}

Remember that, in the body of the function or method, you can use or ignore the parameter. Still, when calling the function or method, you must provide a value for the parameter. Here is an example:

using static System.Console;

void PresentEmployeeSummary(object something)
{
    object employeeName = "Philippe Blayne";
    object hourlySalary = 26.95;
    object yearsOfExperience = 5;

    WriteLine("=//= Employee Record =//=");
    Write("Employee Name: ");
    WriteLine(employeeName);
    Write("Hourly Salary: ");
    WriteLine(hourlySalary);
    Write("Length of Experience: ");
    Write(yearsOfExperience);
    WriteLine(" years");
}

object noNeed = "";

PresentEmployeeSummary(noNeed);

In the same way, you can create a function or method that uses various parameters that are of type object or some are objects while others are not. Here is an example:

void PresentEmployeeSummary(object something, int other)
{
}

object noNeed = "";

PresentEmployeeSummary(noNeed, 0);

Other than that, to provide the fundamental functionality of a class, the object type (or Object class) is equipped with a few methods. These methods are inherited by every data type and any class you use in your application.

Boxing and Un-Boxing

We have mentioned 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 static System.Console;

object Number = 244;
object Thing  = "Professor Kabba";

WriteLine(Number);
WriteLine(Thing);

This would produce:

244
Professor Kabba
Press any key to close this window . . .

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

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

using static System.Console;

int Number = 244;
object Thing  = Number;

WriteLine(Number);
WriteLine(Thing);

This would produce:

244
244
Press any key to close this window . . .

This operation is referred to as unboxing. As you can see, this operation is performed transparently.

Finalizing a Variable

While a constructor, created for each class, is used to instantiate a class, the object class is equipped with a method named Finalize. This method acts as a type of destructor for each class used in an application.

Random Numbers

Introduction to Random Numbers

A number is referred to as random if it has been selected from a pool without a specific pattern to follow. In reality, it is difficult for a number to qualify as random. For this reason, most random numbers are referred to as pseudo-random.

Getting a Random Number

To support the ability to create or choose a random number, the .NET Framework provides a class named Random. This class is defined in the System namespace of the System.dll library. Therefore, if you are planning to use this class, you can first add its namespace in the top of the document.

To start using the Random class, you can declare a variable of that class. The class has two constructors. Here is an example that uses the default constructor:

using System;

Random rand = new Random();

After declaring the variable, you can start getting numbers from it. To help you do this, the Random class is equipped with a method named Next. This method is overloaded with three versions. One of the versions of this method takes no argument. Here is an example of calling it:

Random rand = new Random();

int number = rand.Next();

The System.Next() method generates a randomly selected integer between 0 and a constant named MinValue. You can call this version of the Next() method repeatedly to get random numbers. Here is an example:

using static System.Console;

Random rand = new Random();

int rndNumber1 = rand.Next();
int rndNumber2 = rand.Next();
int rndNumber3 = rand.Next();
int rndNumber4 = rand.Next();
int rndNumber5 = rand.Next();

Write("Random Number: ");
WriteLine(rndNumber1);
Write("Random Number: ");
WriteLine(rndNumber2);
Write("Random Number: ");
WriteLine(rndNumber3);
Write("Random Number: ");
WriteLine(rndNumber4);
Write("Random Number: ");
WriteLine(rndNumber5);
WriteLine("=================================");

Here is an example of what this could produce:

Random Number: 831242334
Random Number: 782179338
Random Number: 1962809432
Random Number: 216011046
Random Number: 124514999
=================================
Press any key to close this window . . .

The Seed of a Random Number

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

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. It takes as argument an integer. 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 5 random numbers between 0 and 100:

using static System.Console;

Random rand = new Random();

int rndNumber1 = rand.Next(100);
int rndNumber2 = rand.Next(100);
int rndNumber3 = rand.Next(100);
int rndNumber4 = rand.Next(100);
int rndNumber5 = rand.Next(100);

Write("Random Number: ");
WriteLine(rndNumber1);
Write("Random Number: ");
WriteLine(rndNumber2);
Write("Random Number: ");
WriteLine(rndNumber3);
Write("Random Number: ");
WriteLine(rndNumber4);
Write("Random Number: ");
WriteLine(rndNumber5);
WriteLine("=================================");

Here is an example of what this could produce:

Random Number: 8
Random Number: 17
Random Number: 69
Random Number: 59
Random Number: 84
=================================
Press any key to close this window . . .

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. 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 static System.Console;

Random rand = new Random();

int rndNumber1 = rand.Next(6, 18);
int rndNumber2 = rand.Next(6, 18);
int rndNumber3 = rand.Next(6, 18);
int rndNumber4 = rand.Next(6, 18);
int rndNumber5 = rand.Next(6, 18);

Write("Random Number: ");
WriteLine(rndNumber1);
Write("Random Number: ");
WriteLine(rndNumber2);
Write("Random Number: ");
WriteLine(rndNumber3);
Write("Random Number: ");
WriteLine(rndNumber4);
Write("Random Number: ");
WriteLine(rndNumber5);
WriteLine("=================================");

Here is an example of what this could produce:

Random Number: 11
Random Number: 9
Random Number: 7
Random Number: 15
Random Number: 10
=================================
Press any key to close this window . . .

Topics on Objects

Introduction

As mentioned previously, any value or object you use in your application is referred to an object. To support objects, the .NET Framework provides a class named Object. This is the most fundamental class of any C# applcation and this class serves an the ancester to all values and classes you will use in your applications. If you create a class in your application, that class is implicitly derived from Object. If you want to be explicit, you can indicate this by writing : Object on the right side of the name of the class you are creating. Here is an example:

public class Person : Object
{
}

We also saw that, to support objects, the C# language provides a data type named object. This data type is simply a type-defined from the .NET Framework's Object class. Both the Object class and the object have the primary characteristics (properties, methods, etc) of any object.

Stringing an Object

A string is the most common value in an application. Sometimes, when you have a value of a certain type, you may want to convert that value to a string. To assist you with converting a value to a string, the Object class is equipped with a method named ToString(). 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 or double. Probably the best way to rely on this method is to override it in your own class. Here is an example:

abstract public class Vehicle
{
    public string Make { get; set; }
    public string Model { get; set; }
    public int Year { get; set; }
}

public class Van : Vehicle
{
    public override string ToString()
    {
        return this.Year + " " + this.Make + " " + this.Model;
    }
}

The Type Class

Introduction

When studying conditional statements, we saw how to check the value held by a variable. In some cases, when you have a variable, you may need to identify the name of the class of that variable. To assist you with this, the .NET Framework provides an abstract class named Type. The Type class is created in the System namespace. Because Type is an abstract class, you cannot declare a variable of it.

The Type of a Class

To assist you with finding out the data type or the class of a variable, the C# language provides an operator named typeof. Its formula is:

Type type = typeof(data-type | class-name);

typeof is a unary operator. That is, it acts on one operand. The operand can be a known primitive data type or a class. If you pass a C# data type (such as double or int with which we are familiar already) as the operand, the typeof operator produces the equivalent .NET Framework type. In reality, the typeof operator produces the Type name of its operand.

The Type GetType() method can also return the data type of the variable that called it. If the variable that calls this method is of a primitive C# data type, this method returns its .NET Framework equivalent. Here is an example of calling this method:

using static System.Console;

Type tp = typeof(int);

Write("The type of the int is ");
WriteLine(tp);
WriteLine("=========================================");

This would produce:

The type of the int is System.Int32
=========================================
Press any key to close this window . . .

The Type of an Object

You will usually need the services of the Type class to know the data type of a variable or of an argument to a method. To make this possible, the Object class is equipped with a method named GetType. Its syntax is:

public Type GetType();

This method takes no argument and returns the name of the class. Here is an example:

using static System.Console;

Square sqr = new Square(1.00);
Type tp = sqr.GetType();

Write("The type of the object is ");
WriteLine(tp);
        
WriteLine("=============================");

public class Square
{
    public Square(double side)
    {
        Side = side;
    }

    public double Side { get; set; }

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

This would produce:

The type of the object is Square
=============================
Press any key to close this window . . .

The Base Type of a Class

The Type.GetType() method gives you the name of the class of a variable. If the class is derived from another class and you want to know the name of its parent class, the Type class can help you, using a property named BaseType. Here is an example of accessing it:

using static System.Console;

var rect = new Rectangle(1.00, 2.00);
Type tp = rect.GetType();

Write("The base type of the rectangle is ");
WriteLine(tp.BaseType);
        
WriteLine("=============================");

public class Square
{
    public Square(double side)
    {
        Side = side;
    }

    public double Side { get; set; }

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

public class Rectangle : Square
{
    public Rectangle(double width, double height)
         : base(width)
    {
        Height = height;
    }

    public double Height { get; set; }

    public double Area
    {
        get
        {
            return Side * Height;
        }
    }
}

This would produce:

The base type of the rectangle is Square
=============================
Press any key to close this window . . .

The Assembly a Type Belongs To

If a class is defined in a library or an assembly, you may want to know what that assembly is. To assist you with getting this information, the Type class is equipped with a property named Assembly.

When accessing the Type.Assembly property, make sure the class of the variable you are using has a formal assembly. Otherwise you would receive an error.

The Full Name of a Type

To get the complete name of the class of a variable without the assembly, use the Type.FullName property.

The Namespace of a Type

Besides the assembly in which the class of a variable exists, you may want to know the namespace in which that class is defined. To let you get this information, the Type class is equipped with the Namespace property.

Finding Out Whether a Type is a Class or an Abstract

Sometimes when using a type, you may want to know whether it is a simple regular class, an abstract class, an enumeration, or another type we haven't studied yet. To assist you with checking this, the Type class provides various Boolean properties such as IsAbstract or IsClass.

Other Built-In Types

The Convert Class

We already know that, to convert a numeric value to text, you can call a method named ToString applied to the value or its variable. To support the conversion of a value from one type to another, the .NET Framework provides a static class named Convert. This class is equipped with various static methods; they are so numerous that we cannot review all of them.

To adapt the Convert class to each C# data type, the class is equipped with a static method whose name starts with To, ends with the .NET Framework name of its type, and takes as argument the type that needs to be converted. Based on this, to convert a value to a double type, you can call the ToDouble() method and pass the value as argument. Its syntax is:

public static int ToDouble(value);

Here are examples of calling this method:

using static System.Console;

WriteLine("Business Accounting");
WriteLine("==========================================================");
WriteLine("Provide the value to create a business accounting report");
WriteLine("----------------------------------------------------------");
Write("Rent:             ");
double rent = Convert.ToDouble(ReadLine());
Write("Supplies:         ");
double supplies = Convert.ToDouble(ReadLine());
Write("Salaries:         ");
double salaries = Convert.ToDouble(ReadLine());
Write("Revenues Sources: ");
double revenues = Convert.ToDouble(ReadLine());
Write("Other Expenses:   ");
double otherExpenses = Convert.ToDouble(ReadLine());

double totalExpenses = salaries + supplies + rent + otherExpenses;
double netIncome = revenues - totalExpenses;

WriteLine("==========================================================");
WriteLine("Business Accounting");
WriteLine("----------------------------------------------------------");
WriteLine("Accounting Report");
WriteLine("Total Expenses:   {0}", totalExpenses);
WriteLine("Net Income.Text:  {0}", netIncome);
WriteLine("==========================================================");

Here is an example of running the application

Business Accounting
==========================================================
Provide the value to create a business accounting report
----------------------------------------------------------
Rent:             12500
Supplies:         12545
Salaries:         535775
Revenues Sources: 1528665
Other Expenses:   327448
==========================================================
Business Accounting
----------------------------------------------------------
Accounting Report
Total Expenses:   888268
Net Income.Text:  640397
==========================================================

Press any key to close this window . . .

Asserting a Condition

Consider the following code:

using static System.Console;

WriteLine("Provide the following pieces of information.");
WriteLine("--------------------------------------------");
Write("Employee Name: ");
string? strEmployeeName = ReadLine();
Write("Hourly Salary: ");
double hSalary = double.Parse(ReadLine()!);

WriteLine("============================================");
WriteLine("Payroll Summary");
WriteLine("--------------------------------------------");
WriteLine("Employee Name: {0}", strEmployeeName);
WriteLine("Hourly Salary: {0}", hSalary);
WriteLine("============================================");

Here is an example of running the application

Provide the following pieces of information.
--------------------------------------------
Employee Name: Jules Roberts
Hourly Salary: -22.65
============================================
Payroll Summary
--------------------------------------------
Employee Name: Jules Roberts
Hourly Salary: -22.65
============================================

Press any key to close this window . . .

Sometimes, in the flow of your application, you want to make sure that a certain condition is true or false otherwise it may be a waste of time to continue with the other operations. To assist you with this, the .NET Framework provides a static class named Debug

public static class Debug

The Debug class is equipped with a method named Assert. This Debug.Assert() is overloaed with six versions. One of the versions uses the following syntax:

public static void Assert (bool condition);

This version takes a Boolean expression as argument. That expression is exactly like any we have seen so far. Here is an example:

using static System.Console;

WriteLine("Provide the following pieces of information.");
WriteLine("--------------------------------------------");
Write("Employee Name: ");
string? strEmployeeName = ReadLine();
Write("Hourly Salary: ");
double hSalary = double.Parse(ReadLine()!);

Debug.Assert(hSalary > 0);

WriteLine("============================================");
WriteLine("Payroll Summary");
WriteLine("--------------------------------------------");
WriteLine("Employee Name: {0}", strEmployeeName);
WriteLine("Hourly Salary: {0}", hSalary);
WriteLine("============================================");

Here is an example of running the application

Provide the following pieces of information.
--------------------------------------------
Employee Name: Jules Roberts
Hourly Salary: -22.25
Process terminated. Assertion failed.
   at Program.<Main>$(String[] args) in E:\Users\monye\source\repos\Consoles\Exercise1\Exercise1\Exercise.cs:line 8

Press any key to close this window . . .

As you can see, if the value passed to the Debug.Assert() method is false, the application produces a message and stops. Also notice that we provided a very simple Boolean expression. In reality, you can provide an expression as complex as you want, as long as it can be evaluated to true or false.

The Environment Class

Introduction

The .NET Framework provides a static class named Environment. This class quickly and easily gives you some information about the application that is currently running and some objects you can use in your application. The Environment class is defined in the System namespace. This means that you don't have to do anything to access it, since it is automatically available whenever you create a C# application.

Getting to the Next Line

By default, when an operation has been performed on a string, the caret remains on the line after the operation. In some cases, you want to move the caret or the next operation to the next line. To assist you with this operation, the Environment class provides a read-only property named NewLine:

public static string NewLine { get; }

Simply access this property where you want to ask the compiler to advance to the next line. Here is an example:

using static System.Console;

Write(Environment.NewLine);

You can also use the + operator to add the Environment.NewLine property to a string. Here are examples:

using static System.Console;

int GetViolation()
{
    Write("Type of Traffic Violation" + Environment.NewLine +
          "1 - Slow Driving" + Environment.NewLine +
          "2 - Fast Driving" + Environment.NewLine +
          "3 - Aggressive Driving" + Environment.NewLine +
          "4 - Unknown - Other" + Environment.NewLine +
          "--------------------------------------" + Environment.NewLine +
          "Type of violaction (1-4):      ");
    return int.Parse(ReadLine());
}

(int abc, string xyz) Evaluate(int problem)
{
    (int a, string b) result;

    switch (problem)
    {
        case 1:
            result = (0, "Slow Driving");
            break;
        case 2:
            result = (100, "Fast Driving");
            break;
        case 3:
            result = (125, "Aggressive Driving");
            break;
        default:
            result = (50, "Unknown - Other");
            break;
    }

    return result;
}

int infraction = GetViolation();
(int amount, string message) ticket = Evaluate(infraction);

Write(Environment.NewLine);

Write("Ticket Summary" + Environment.NewLine +
      "======================================" + Environment.NewLine);
Write("Traffic Violation: {0}" + Environment.NewLine, ticket.message);
Write("Ticket Amount:     {0}" + Environment.NewLine, ticket.amount);

Here is an example of running the application

Type of Traffic Violation
1 - Slow Driving
2 - Fast Driving
3 - Aggressive Driving
4 - Unknown - Other
--------------------------------------
Type of violaction (1-4):      3

Ticket Summary
======================================
Traffic Violation: Aggressive Driving
Ticket Amount:     125

Press any key to close this window . . .

Getting the Machine Name

It used to be difficult to know the name of the computer on which your application is running. To let you easily get this information, the Environment class provides a property named MachineName

public static string MachineName { get; }

Here is an example of accessing this property:

using static System.Console;

WriteLine("Current Machine Name: {0}", Environment.MachineName);
WriteLine("======================================");

Here is an example of what the above code would produce:

Current Machine Name: DESKTOP-PD7NQLM
======================================

Press any key to close this window . . .

Getting the Operation System's Version

To assist you with knowing the version of the operating system on which the application is running, the Environment class provides the OSVersion property

public static OperatingSystem OSVersion { get; }

Here is an example of accessing this property:

using static System.Console;

WriteLine("Current Operating System: {0}", Environment.OSVersion);
WriteLine("===========================================================");

Here is an example of what the above code would produce:

Current Operating System: Microsoft Windows NT 10.0.19045.0
===========================================================

Press any key to close this window . . .

Getting the Current User's name

At any time, if you want to know the user name of the person who is currently using your application, you can get the value of the UserName property of the Environment class:

public static string UserName { get; }

The Microsoft Windows operation system is usually installed on the C: drive with most of its drivers in a folder named System32 that is located either under Windows or WinNT. This full path of the driver's main folder is referred to as the system directory.

Getting the System Directory

To assist you with finding out the path to the system directory, the Environment class is equipped with a property named SystemDirectory:

public static string SystemDirectory { get; }

Here is an example of accessing this property:

using static System.Console;

WriteLine("System Directory: {0}", Environment.SystemDirectory);
WriteLine("=================================================");

Here is an example of what the above code would produce:

System Directory: C:\WINDOWS\system32
=================================================

Press any key to close this window . . .

Getting the Directory of the Current Application

To let you identify the directory from which the current application is running, or to let you specify the directory for a new application, the Environment class provides a property named CurrentDirectory:

public static string CurrentDirectory { get; set; }

Notice that this is a read/write property. Here is an example that gets the directory of the application that is accessing this property:

using static System.Console;

WriteLine("Current Directory: {0}", Environment.CurrentDirectory);
WriteLine("=====================================================================");

Here is an example of what the above code would produce:

Current Directory: E:\Users\jchan\source\repos\Exercise1\Exercise1\bin\Debug\net8.0
=====================================================================

Press any key to close this window . . .

Previous Copyright © 2001-2024, FunctionX Monday 04 December 2024 Next