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

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

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

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:

using System;

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

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 values. To support this operation, the Object class provides its children with an overloaded Boolean method named 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 static System.Console;

int integer = 248;
int number = 248;

WriteLine("========================");
WriteLine("Integer: {0}", integer);
WriteLine("Number:  {0}", number);

WriteLine("------------------------");
if (integer.Equals(number))
    WriteLine("Those numbers are equal.");
else // if (integer.Equals(number) == false)
    WriteLine("Those numbers are different.");
WriteLine("========================");

This would produce:

========================
Integer: 248
Number:  248
------------------------
Those numbers are equal.
========================
Press any key to continue . . .

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. Here is an example:

using static System.Console;

int distance = 928_304;
int length = 928_304;

WriteLine("=========================");
WriteLine("Distance: {0}", distance);
WriteLine("Length:   {0}", length);
WriteLine("-------------------------");

if(int.Equals(distance, length))
    WriteLine("Those numbers are equal.");
else // if (int.Equals(distance, length))
    WriteLine("Those numbers are equal.");
WriteLine("=========================");

This would produce:

=========================
Distance: 928304
Length:   928304
-------------------------
Those numbers are equal.
=========================

Press any key to close this window . . .

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 method on variables declared from your own class, you should provide your own implementation of this method.

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

The Environment Class

Introduction

The .NET Framework provides a static class named Environment. This class quickly and easily gives 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 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.

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.

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.

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.


Previous Copyright © 2001-2022, FunctionX Sunday 14 November 2021 Next