Home

Introduction to Classes

Classes Fundamentals

Introduction

A class is a technique of using one variable or a group of variables as a foundation for an object.

Naming a Class

When creating a class, you must give it a name. The name primarily follows the same rules as the variables. You can then add your own rules. In our lessons:

Creating a Class

To create a class start with a keyword named class followed by a name as mentioned previously. The name of a class is followed by curly brackets. Here is an example of a class named House:

class House
{
}

The creation of a class can be included in the script element of the head section of a class. Here is an example:

<%@ Page Language="C#" %>
<html>
<head>

<script runat="server">
class House
{
}
</script>

<title>Exercise</title>
</head>
<body>

</body>
</html>

Introduction to Using a Class

Creating an Object

To use a class in your project, you must first declare a variable for it. Declaring a variable of a class is also referred to as creating an object or creating an instance of a class. To declare a variable for a class, you can use the var keyword. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
class House
{
}
</script>

<title>Exercise</title>

</head>
<body>

<%
    var casa . . .
%>

</body>
</html>

Alternatively, instead of the var keyword, you can use the name of the class to declare the variable. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
class House
{
}
</script>

<title>Exercise</title>

</head>
<body>

<%
    House casa . . .
%>

</body>
</html>

A Null Object

A variable that has been declared for a class but has not yet received a value is referred to as a null object. To create a null object, when declaring the variable, use the name of the class, followed by a name for the variable, and assign the null keyword to it. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
class House
{
}
</script>

<title>Exercise</title>

</head>
<body>

<%
    House prop = null;
%>

</body>
</html>

Unlike a value type, the class must not use a question mark.

If a variable of a class was previously declared and initialized but, one way or another, the values have been removed or deleted, the variable is also referred to as a null object. Most of the times, you will only be interested to find out whether an object is null.

Reference Types

When you declare a variable for a class, the variable must be stored in a section of memory named the heap. To make this request, you use an operator called new to initialize the variable. The operator is followed by the name of the class and parentheses. Here are two examples:

<%@ Page Language="C#" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
class House
{
}
</script>

<title>Exercise</title>

</head>
<body>

<%
    var casa = new House();
    House prop = new House();
%>

</body>
</html>

A variable initialized using the new operator is referred to as a reference variable.

Sharing a Class

If you want your class to be accessible to code written in other languages but on the same project, precede the class keyword with the public keyword when creating it. Here is an example:

<script runat="server">
public class House
{
}
</script>

Introduction to the Properties of a Class

The section between the curly brackets, { and }, of a class is referred to as its body. In the body of a class, you can create the items that make up the class. These items are called properties or fields. Each property starts like a declared variable without an initialization: It has a data type and a name. If the name is in one word, the first letter is in uppercase. If the name is in different words, each parts starts in uppercase. Here are examples:

<script runat="server">
public class House
{
    string Name;
    int Domain;
    byte Community;
}
</script>
Author Note

New Convention:

From now on, in our lessons, to refer to a field or property that belongs to a class, we may write

class-name.property-name

This means that we are referring to the member property-name that is in the class class-name.

Garbage Collection

When a variable of a class is not needed anymore, the object must be deleted and the memory it was using must be gotten back. This is called garbage collection. The .NET Framework solves the problem of garbage collection by "cleaning" the memory after you.

Access Modifiers of Class Members

The Private Members of a Class

The parts of an object fall into two main categories: those that are public and those that are hiddent. The parts that are hidden or must be hidden are referred to as private. To create a hidden object, start it with a keyword named private. Here is an example:

<script runat="server">
public class House
{
    private int garage;
}
</script>

The Public Members of a Class

The parts of a class that must be accessed outside the class are referred to as public. To create a public object, precede its data type a keyword named public. Here are examples:

<script runat="server">
public class House
{
    public string PropertyNumber;
    public int Bedrooms;
    public decimal MarketValue;
    private int garage;
}
</script>

If you omit or forget the access level of a member of a class, the member is automatically made private. To reduce confusion, you should always specify the access level of a member.

The Internal Members of a Class

If you want to create a member of a class so that only objects of the same project can access that member, mark it with the internal keyword. The differences between these keywords can be resumed as follows:

  If a class member is marked as
  public internal private
Members of its class can access this member Yes Yes Yes
Members of this project, including outside of the class, can access this member Yes Yes No
Objects outside of this project can access this member Yes No No

Initializing an Object

The Period Operator

After creating a member of a class, to access it from outside the class, first declare a variable as we saw earlier. To actually access a property, use the period operator ".". You can then assign a value to the property. Here is an example:

<%
    var residence = new House();
    
    residence.PropertyNumber = 283795;
    residence.PropertyType = "Single Family";
    residence.Stories = 3;
    residence.Bedrooms = 5;
    residence.Bathrooms = 3.5;
    residence.MarketValue = 652880;
%>

Once a property or a field has been initialized, you can use the period operator to access it and retrieve its value. Here are examples:

<%@ Page Language="C#" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
public class House
{
    public long PropertyNumber;
    public string PropertyType;
    public byte Stories;
    public int Bedrooms;
    public float Bathrooms;
    public double MarketValue;
}
</script>

<title>Exercise</title>

</head>
<body>

<%
    var residence = new House();
    
    residence.PropertyNumber = 283795;
    residence.PropertyType = "Single Family";
    residence.Stories = 3;
    residence.Bedrooms = 5;
    residence.Bathrooms = 3.50F;
    residence.MarketValue = 652880D;

    Response.Write("=--= Altair Realtors =--=");
    Response.Write("<br>Properties Inventory");
    Response.Write("<br>Property #:  ");
    Response.Write(residence.PropertyNumber);
    Response.Write("<br>Property Type:  ");
    Response.Write(residence.PropertyType);
    Response.Write("<br>Stories:       ");
    Response.Write(residence.Stories);
    Response.Write("<br>Bedrooms:       ");
    Response.Write(residence.Bedrooms);
    Response.Write("<br>Bathrooms:       ");
    Response.Write(residence.Bathrooms);
    Response.Write("<br>Market Value:  ");
    Response.Write(residence.MarketValue);
%>

</body>
</html>

This would produce:

Initializing an Object

Using an Anonymous Type

You can declare a variable that resembles an instance of a class and initialize it as you see fit. This is referred to as an anonymous type. To use it, declare the variable using the var keyword and use the new operator to allocate memory for it.

Classes and Functions

A Function that Returns an Object

A function can be made to return an object. Remember that, when creating a function, if it is not returning a known value, you must mark it as void. Otherwise, if the function returns an object, put the name of the class on the left of the function name. In the body of the function, do whatever you want. When the function ends, it must return a value that corresponds to the class. Here is an example:

<script runat="server">
public class Student
{
    public string StudentNumber;
    public string FirstName;
    public string LastName;
    public char   Gender;
}

Student Register()
{
        Student std = new Student();

        std.StudentNumber = "77-3946-84";
        std.FirstName = "Amir";
        std.LastName = "Shalloub";
        std.Gender = 'M';

        return std;
}
</script>

To get the value returned by the function, you can assign its call to an object created from the class. You can then use that returned object. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
public class Student
{
    public string StudentNumber;
    public string FirstName;
    public string LastName;
    public char   Gender;
}

Student Register()
{
        Student std = new Student();

        std.StudentNumber = "77-3946-84";
        std.FirstName = "Amir";
        std.LastName = "Shalloub";
        std.Gender = 'M';

        return std;
}
</script>

<title>Student Registration</title>
</head>
<body>

<%
    Student pupil = new Student();

    pupil = Register();

    Response.Write("<h2>=--= Student Registration =--=</h2>");
    Response.Write("<table border=2><tr><td>Student #:</td><td>");
    Response.Write(pupil.StudentNumber);
    Response.Write("</td></tr><tr><td>First Name:</td><td>");
    Response.Write(pupil.FirstName);
    Response.Write("</td></tr><tr><td>Last Name :</td><td>");
    Response.Write(pupil.LastName);
    Response.Write("</td></tr><tr><td>Gender:</td><td>");
    Response.Write(pupil.Gender);
    Response.Write("</td></tr></table>");
%>

</body>
</html>

This would produce:

A Function that Returns an Object

In our example, we first declared a variable for the class. This is not necessary since the class is initialized in the function that will produce the object. This means that you can directly assign the function call to the variable. Here is an example:

. . .

</head>
<body>

<%
    Student pupil = Register();

    . . .
%>

</body>
</html>

Passing an Object to a Function

A class can be passed to a function. In this case, provide the name of the class and a name for the parameter in the parentheses of the function. As mentioned for the primitive types, you don't have to use the parameter in the body of the function. Here is an example:

<script runat="server">
public class Depreciation
{
    public double Cost;
    public double SalvageValue;
    public double EstimatedLife;
}

void Calculate(Depreciation item)
{
    double number = 94.7085;
    double value  = 4792.04860;

    double addition = number + value;
}
</script>

Otherwise, you can use the parameter in the body of the class. In this case, to access a property of the class, type the name of the parameter followed by a period and the name of the property. Here are examples:

<%@ Page Language="C#" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
public class Depreciation
{
    public double Cost;
    public double SalvageValue;
    public double EstimatedLife;
}

double Calculate(Depreciation item)
{
    double estimate = (item.Cost - item.SalvageValue) / item.EstimatedLife;

    return estimate;
}
</script>

<title>Depreciation: Straight-Line Method</title>
</head>
<body>
<div align="center">
<%
    Depreciation machine = new Depreciation();

    machine.Cost = 17000;
    machine.SalvageValue = 2000;
    machine.EstimatedLife = 5;

    double value = Calculate(machine);

    Response.Write("<h2>Depreciation: Straight-Line Method</h2>");
    Response.Write("<table border=2><tr><td>Machine Cost:</td><td>");
    Response.Write(machine.Cost );
    Response.Write("</td></tr><tr><td>Salvage Value:</td><td>");
    Response.Write(machine.SalvageValue);
    Response.Write("</td></tr><tr><td>EstimatedLife:</td><td>");
    Response.Write(machine.EstimatedLife);
    Response.Write("</td></tr><tr><td>Depreciation:</td><td>");
    Response.Write(Calculate(machine));
    Response.Write("</td></tr></table>");
%>
</div>
</body>
</html>

This would produce:

Passing an Object to a Function

Passing Many Parameters to a Function

As mentioned for regular types, a function can take more than one parameter. One of the parameters can be a class while the other is a regular type. In the body of the class, you don't have to use any of the parameters, or you can use one of them or both.

You can create a function that takes more than one parameter where all parameters are class types. Here is an example of a function with two objects as parameters:

<script runat="server">
public class Machine
{
}

public class Depreciation
{
}

void Calculate(Machine item, Depreciation estimate)
{
}
</script>

Once again, in the body of the class, you can ignore one of the parameters. Here is an example that uses only one of the parameters:

<script runat="server">
public class Machine
{
    public string SerialNumber;
    public string Make;
    public string Model;
    public double Price;
}

public class Depreciation
{
    public double Cost;
    public double SalvageValue;
    public double EstimatedLife;
}

double Calculate(Machine item, Depreciation estimate)
{
    double value = (estimate.Cost - estimate.SalvageValue) / estimate.EstimatedLife;

    return value;
}
</script>

When calling the function, if you don't need a parameter, you can pass it as null. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
public class Machine
{
    public string SerialNumber;
    public string Make;
    public string Model;
    public double Price;
}

public class Depreciation
{
    public double Cost;
    public double SalvageValue;
    public double EstimatedLife;
}

double Calculate(Machine item, Depreciation estimate)
{
    double value = (estimate.Cost - estimate.SalvageValue) / estimate.EstimatedLife;

    return value;
}
</script>

<title>Depreciation: Straight-Line Method</title>
</head>
<body>
<div align="center">
<%
    Depreciation dep = new Depreciation();

    dep.Cost = 5000;
    dep.SalvageValue = 500;
    dep.EstimatedLife = 5;

    double value = Calculate(null, dep);

    Response.Write("<h2>Depreciation: Straight-Line Method</h2>");
    Response.Write("<table border=2><tr><td>Machine Cost:</td><td>");
    Response.Write(dep.Cost );
    Response.Write("</td></tr><tr><td>Salvage Value:</td><td>");
    Response.Write(dep.SalvageValue);
    Response.Write("</td></tr><tr><td>EstimatedLife:</td><td>");
    Response.Write(dep.EstimatedLife);
    Response.Write("</td></tr><tr><td>Depreciation:</td><td>");
    Response.Write(value);
    Response.Write("</td></tr></table>");
%>
</div>
</body>
</html>

This would produce:

Passing Many Parameters to a Function

In the same way, you can create a function that takes many paremeter but you don't have to use those parameters in the body of the function.

Introduction to Built-In Classes

Introduction

To assist you with programming projects, the .NET Framework includes many classes. Some classes are regularly used, almost in every project, some classes are hardly used. We cannot review all .NET built-in classes. Instead, we will introduce and review some classes as they become necessary.

An Object

The most fundamental class used in project is called Object. In C#, this class can be used as object. You can use it to declare a variable for any type. Any way to use it is to pass it as parameter.

A Nullable Object

To suport null values, the .NET Framework provides a class named Nullable. The main purpose of this class is for null to be used as an object.

Enumerations

Introduction

An enumeration is a list of contant numbers where each number receives a name and so each number can be accessed by its name. To create an enumeration, you use the enum keyword, followed by the name of the enumeration, followed by a name for each item of the list. The name of the enumerator and the name of each item of the list follows the rules we reviewed for names. The formula of creating an enumeration is:

enum Enumeration_Name {Item1, Item2, Item_n};

Here is an example of creating an enumeration:

<script language="C#" runat="server">
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
</script>

Declaring an Enumeration Variable

After creating an enumeration, each member of the enumeration holds a value of a natural number, such as 0, 4, 12, 25, etc. In C#, an enumeration cannot hold character values (of type char).

After creating an enumeration, you can declare a variable from it. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
<script language="C#" runat="server">

enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }

</script>
</head>
<body>
<div align="center">

<h3>Exercise</h3>

<%
    HouseType propType;
%>
</body>
</html>

Just as done with the other types, you can use the var keyword to declare a variable of an enumeration type.

Initializing an Enumeration Variable

After declaring a variable for an enumeration, to initialize it, specify which member of the enumeration would be assigned to the variable. You should only assign a member of the enumeration. To do this, on the right side of the assignment operator, type the name of the enumeration, followed by the period operator, and followed by the member whose value you want to assign. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
<script language="C#" runat="server">

enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }

</script>
</head>
<body>
<div align="center">

<h3>Exercise</h3>

<%
    HouseType propType = HouseType.SingleFamily;
%>
</body>
</html>

You can also find out what value the declared variable is currently holding.

Custom Values for the Members of an Enumeration

As mentioned in the introduction, an enumeration is in fact a list of numbers where each member of the list is identified with a name. By default, the first item of the list has a value of 0, the second has a value of 1, and so on. If you don't want the default values, you can specify the value of one or each member of the enumeration. Here is an example:

<script language="C#" runat="server">
    enum HouseType { Unknown = 5, SingleFamily, TownHouse, Condominium }
</script>

In this case, Unknown now would have a value of 5, SingleFamily would have a value of 6 because it follows a member whose value is 1 (thus 5 + 1 = 6). Townhouse would have a value of 7, and Condominium would have a value of 8. You can also assign a value to more than one member of an enumeration. Here is an example:

<script language="C#" runat="server">
    enum HouseType { Unknown = 3, SingleFamily = 12, TownHouse, Condominium = 8 }
</script>

In this case, Townhouse would have a value of 13 because it follows SingleFamily that has a value of 12.

Enumerations Visibility

By default, if you create an enumeration the way we have proceeded so far, it would be available only in the project it belongs to. As done for a class, you can control an enumeration's accessibility outside of its project. This means that you can hide or make it visible outside of its project. To do this, you can precede it with the private or the public keyword. Here is an example:

<script language="C#" runat="server">
public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}
</script>

An Enumeration as a Member Variable

After creating an enumeration, you can use it as a data type to declare a variable. To create a property that is of an enumeration type, follow the same rules as done for the primitive types: the name of the enumeration, followed by the name of the variable, and followed by a semi-colon. Here is an example:

<script language="C#" runat="server">

public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}

public class House
{
    public HouseType PropertyType;
}
</script>

Once the member variable has been created, you can use it. To initialize it, assign the desired member of the enumeration to it. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
<script language="C#" runat="server">
public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}

public class House
{
    public HouseType PropertyType;
}
</script>
</head>
<body>
<div align="center">

<h3>Exercise</h3>

<%
    House prop = new House();

    prop.PropertyType = HouseType.SingleFamily;
%>
</body>
</html>

Passing an Enumeration as Argument

As mentioned already, once an enumeration has been created, it becomes a type. It can be passed as argument and/or it can be returned from a function.

Returning an Enumeration From a Function

To create a function that returns an enumeration, specify its return type as the name of the enumeration.