Based on a brief definition we had in the first lesson, we have been using classes in a very introductory
manner. This was necessary
because everything in C# is built around a concept of class. A class can be more
elaborate than what we have been acquainted to. A class is a technique of creating one
or a group of variables to be used as a foundation for a more detailed variable. A class must be created in a computer file. You can create such a file
with only one class or you can create many classes inside of one file.

To create a class, you start with the class keyword
followed by a name and its body delimited by curly brackets. Here is an example of a class called Book:

class Book
{
}

Practical
Learning: Introducing Classes

Start Microsoft Visual C# or Visual Studio .NET

On the main menu, click File -> New -> Project

If necessary, in the Project Types list of the New Project dialog box,
click Visual C# Projects

In the Templates list, click Empty Project

In the Name text box, replace the name with DeptStore1 and specify
the desired path in the Location

Click OK

To create a source file for the project, on the main menu, click Project
-> Add New Item...

In the Add New Item dialog box, in the Templates list, click Code File

In the Name text box, delete the suggested name and replace it with Exercise

Like any normal variable, to use a
class in your program, you can first declare a variable for it (when we study
static fields, we will see that you can use a class without primarily
declaring it). Like the variables we
introduced in the previous lesson, to declare a variable of a class, type its name followed by
a name for the variable. For example, to declare a variable of the above Book in another class called
NewProject, you could type the following:

The variables we have declared so far are called value
variables. This is because such a variable of a primitive type holds its value. The C# language supports
another type of variable. This time, when you declare the variable, its name
doesn't hold the value of the variable; it holds a reference to the address
where the actual variable is stored. This reference type is the kind used to declare a variable for a class.

To use a variable as reference, you must initialize it using
an operator called new. Here is an example:

Unlike its sisters the C and the C++ languages, C# was
developed with the idea of working complementarily with other languages such as
C++, Visual Basic, and J#. In other words, code from these other languages
should be able to "read" or access code written in a C# application.
To make this possible, a C# class can be created as a public object.

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

When you initialize a variable using the new operator, you
are in fact asking the compiler to provide you some memory space in the heap
memory. The compiler is said to "allocate" memory for your variable.
When that variable is no longer needed, such as when your program closes, it
(the variable) must be removed from memory and the space it was using can be
made available to other variables or other programs. This is referred to as
garbage collection. In the past, namely in C/C++, this was a concern for
programmers because they usually had to remember to manually delete such a
variable (a pointer) and free its memory.

The .NET Framework solves the problem of garbage collection
by letting the compiler "clean" memory after you. This is done
automatically when the compiler judges it necessary so that the programmer
doesn't need to worry about this issue.

A Program With Various Files

Instead of only one file, you can create a program with many
of them. Each file can contain different assignments that, when put together,
can create an application as complete as possible. To make this possible, you
can create each file with a name and the extension .cs. To compile the project,
after typing csc, you can list the files separated by commas.

In C++ and Pascal, if you create a class CA in
a certain file FA and want to access anything included in that class from another file FB, you
must type #include (C/C++) or uses (Pascal) followed by the name of the file
FA somewhere in the top section of the file FB.

Class' Fields

Introduction

Consider the Book class defined earlier:

public class Book
{
}

The section between the curly brackets of a class is
referred to as its body. In the body of a class, you can create a list of
the parts that make up the class. Each of these parts must be a complete
variable with a name and a data type. For example, here are the
characteristics that make up a book, declared as the parts of the above
Book class and each declared as a variable:

The variables declared in the body of a class are
referred to as its member variables and each member variable is referred
to as a field. The fields can be any type
we have seen in the previous lesson. Based on this, when creating a class,
it is your job to decide
what your object is made of.

Practical
Learning: Introducing Class Members

Imagine you want to write a (console-based) program
for a department store and the customer has given you a preliminary
catalog as follows:

Stock #: 437876
Women Spring Coat Classy
Unit: $145.55

Stock #: 79475
Women Bathing Suit Sandstone
$75.55

Stock #: 74797
Women Suit Exchange
$225.75

Stock: 68432
Men Jacket
$115.85

Stock #: 75947
Children Summer Hat
$17.95

Stock #: 48746
Children Playground Dress
$24.55

Each item in this catalog is represented by its Stock
number, its name or description, and its price. Based on this, you can
create a class that represents each item.

The parts of an object fall into two main
categories: those you can touch and those you don't have access to. For example,
for a car parked at the mall, you can see or touch its doors and its tires but
you don't see its engine or its spare tire, you don't even know if it has one. The parts of an object
that you have access to are referred to as public. Those you can't see or touch
are referred to as private.

A C# class also recognizes that some parts of a class can be
made available to other classes and some other parts can be hidden from other
classes. A part that must be hidden from other classes is private and it can be
declared starting with the private keyword. If you declare a member
variable and want to make it available to other classes,
you must start its name with the public keyword. The public and private
keywords are referred to as access level.

By default, if you declare a member variable (or anything
else) in a class but don't specify its access level, the member is considered
private and cannot be accessed from outside, that is by a non-member, of that
class. Therefore, to make a member
accessible by other classes, you must declare it as public.

You can use a mix of public and private members
in a class and there is no rule on which access level should be listed first or last. Here is an example:

Unlike C/C++, in C#, you can create a constant variable in a
class. As done in Lesson 2 when studying
variables, to declare a constant variable, type the const
keyword to the left of the variable. Once again, when declaring a constant, you must initialize it with an
appropriate constant value. Here is an example:

Enter the value in meters: 25.38
25.38m = 999.2106in
Do you want to perform another conversions(y/n)? y
Enter the value in meters: 44.68
44.68m = 1759.0516in
Do you want to perform another conversions(y/n)? Y
Enter the value in meters: 18.28
18.28m = 719.6836in
Do you want to perform another conversions(y/n)? n

Practical Learning: Creating a Constant

To start a new project, on the main menu, click File -> New ->
Project

In the Templates section, click Empty Project

Set the Name to IceCream1 and press Enter

To add a source file, on the main menu, click Project -> Add New
Item...

In addition to what we have learned so far, to create two constants, type
the following:

When creating a member variable of a class, one of the
decisions you make consists of deciding how the field would get its
value(s). Sometimes you will allow the clients of the class to change the
values of the field. In some other cases, you may want the field to only
hold or present the value without being able to change it. This can still
allow the clients to access the field and its value but on a read-only
basis.

To create a field whose value can only be read,
precede its data type, during declaration, with the readonly
keyword. Here is an example:

public readonly double PI;

After declaring the variable, you should initialize
it. You have two main alternatives. You can initialize the field when
declaring it. Here is an example:

If the value held by a read-only field is gotten from
an expression, then the field must be initialized in the(a) construction
with the desired expression. Based on this, the following code will not
compile:

In the previous section, we saw that a constant
variable must be initialized when it is created. Although a read-only
variable seems to follow the same rule, it doesn't. Remember that you
don't need to initialize a read-only variable when you declare it since
you can do this in the(a) constructor of the class. Also, because a
constructor can be overloaded, a read-only field can hold different values
depending on the particular constructor that is accessed at a particular
time but the value of a constant variable cannot change: it is initialized
once, in the class (or in a method) and it keeps that value throughout the
class (or method).

Static Fields

Imagine you create a class called Book. To access it in the
Main() function, you can declare its variable, as we have done so far. A
variable you have declared of a class is also called an instance of the class. In the same way, you can declare
various instances of the same class as necessary:

using System;
public class Book
{
public string Title;
public string Author";
public short YearPublished;
public int NumberOfPages;
public char CoverType;
}
public class NewProject
{
static void Main()
{
Book written = new Book();
Book bought = new Book();
}
}

Each one of these instances gives you access to the
members of the class but each instance holds the particular values of the
members of its instance. Consider the results of the following program:

All of the member variables and methods of classes we
have used so far are referred to as instance members because, in
order to access them, you must have an instance of a class declared in
another class in which you want to access them.

C# allows you to declare a class member and refer to
it regardless of which instance of an object you are using. Such a member
variable is called static. To declare a member variable of a class
as static, type the static keyword on its left. Whenever you have a
static member, in order to refer to it, you must "qualify" it in
the class in which you want to call it. Qualifying a member means you must
give its complete location, including the name of its class and the
namespace (if any) in which its class was created. Here is an example:

Notice that when a member variable has been declared
as static, you don't need an instance of the class to access that member
variable outside of the class. Based on this, if you declare all members
of a class as static, you don't need to declare a variable of their class
in order to access them. In the following example, the Title and Author
fields of the Book class are accessed from the Program class without using
an instance of the Book class:

As we saw in Lesson 6, you can also declare member
variables of the main class as static. If you are referring to a static member variable in
the same class in which it was declared, you don't have to qualify it.
Here is an example:

Save the file, compile and test it at the Command Prompt. Here is an
example:

Return to Notepad

Static Methods

Like a member variable, a method of a class can be define as
static. This means that this particular method can access any member of the
class regardless of the instance if there are many instances of the class
declared.

To define a method as static, type the static keyword
to its left. Here is an example:

The ReadLine(), the Write(), and the WriteLine()
methods of the Console class that we have used so far are examples of static
methods. There are many others in the C# language. The documentation can guide
you to know what method of what class is static or not.

We have mentioned two techniques of accessing the members of
a class, one consisted of declaring a variable of the class, the other had to do
with static members. None of these techniques is important if you want to access
a field or method of a class from another method of the same class. We know
already that the members of a class are made available to all other members of
the same class without being declared or qualified. Consider the following
class:

When the Area variable is used in the Show() method,
there are two variables available and named Area. It makes it confusing to know
what particular variable is being accessed. C#, like many other languages,
provides a special member of a class that allows you to specify the member of a
class when accessing it. This member is called this.

When using the this member variable (in C/C++, it is
a pointer), you can access any member of a class within any method of the same
class. Here is an example:

A structure is an enhanced version of the primitive data
types we have used in previous lessons. The difference is that, like a class, a
structure is created from one primitive type or by combining various primitive
types, resulting in an advanced data type that is not inherently built in the C#
language.

To create a structure, you use the same formula as a class
but with the struct keyword. Here is an example of a structure:

struct Box
{
}

Like a class, a structure can have fields. They are listed
in the body of the structure.

Like any other data type, to use a structure, you can first
declare a variable from it. Like primitive data types and unlike a class, a
structure is a value type. Therefore, you can declare it without the new
keyword. Here is an example:

When you declare a variable of a class, a special
method must be called to initialize the members of that class. This method
is automatically provided for every class and it is called a constructor.
Whenever you create a new class, a constructor is automatically provided
to it. This particular constructor is called the default
constructor. You have the option of creating it or not. Although a constructor is created for your class, you can
customize its behavior or change it tremendously.

A constructor holds the same name as its class and doesn't return
any value, not even void. Here is an example:

public class Book
{
Book()
}

Like every method, a constructor can be equipped with
a body. In this body, you can access any of the member variables (or
method(s)) of the same class. When introducing classes other than the main
class, we saw that, to use such a class, you can declare its variable and
allocate memory using the new operator. You can notice that we always
included the parentheses when declaring such a variable. Here is an
example:

This shows that, when a class has been instantiated,
its constructor is the first method to be called. For this reason, you can
use a constructor to initialize a class, that is, to assign default values
to its member variables. When a constructor is used to initialize a
variable declared for a class. That constructor is referred to as an
instance constructor.

Practical
Learning: Constructing a Class

Start a new file in Notepad and, in the empty file, type the following:

In the previous section, we saw that there is always a
default constructor for a new class that you create; you just the option of
explicitly creating one or not. The default constructor as we saw it doesn't
take arguments: this is not a rule, it is simply assumed. Instead of a default
constructor, you may want to create a constructor that takes an argument. Here
is an example:

public class Quadrilateral
{
public Quadrilateral(double side)
{
}
}

With this type of constructor, when you declare an instance
of the class, you can use this new constructor to initialize the class. Here is
an example:

If you create one constructor for your class and pass at
least one argument to that constructor, the automatic default constructor
created by the compiler disappears. This implies that if you declare an instance
of the class and use the default constructor to initialize it, you would receive
an error when you compiler the program. Based on this rule, the following
program will not compile:

Like the above described instance constructors, a static
constructor is used to initialize a class. The main difference is that a static
constructor works internally, in the class. Therefore, it is not used to
initialize a variable of the class and you can never declare a variable of a class using a static constructor.

To make a constructor static, when creating it, type the
static keyword to its left. Here is an example:

In the above class, a static constructor is created for the
class but the default constructor is still available and it is used to
instantiate the class.

Constructor Overloading

A constructor is the primary method of a class. It allows
the programmer to initialize a variable of a class when the class is
instantiated. A constructor that plays this role of initializing an instance of
a class is also called an instance constructor. Most of the time, you don't even
need to create a constructor, since one is automatically provided to any class
you create. Sometimes too, as we have seen in some classes, you need to create
your own class as you judge it necessary. And sometimes, a single constructor
may not be sufficient. For example, when creating a class, you may decide, or
find out, that there must be more than one way for a user to initialize a
variable.

Like any other method, a constructor can be overloaded. In
other words, you can create a class and give it more than one constructor. The
same rules used on overloading regular methods also apply to constructors: the
different constructors must have different number of arguments or a different
number of arguments.

While a constructor is a method used to initialize an
instance of a class, a destructor is used to destruct an instance of class when
that variable is not used anymore. Like the constructor, the destructor has the
same name as the class. To indicate that the method is a destructor, its name is
preceded with a tilde.

Like a (default) constructor, a destructor is automatically
created for your class but you can also create it if you want. A class can have
only one constructor. If you don't create it, the compiler would create it for
your class. If you create it, the compiler would not create another. A
destructor cannot have an access level. A destructor is called when the memory
that a class was used is no longer needed. This is done automatically by the
compiler. For this reason, you will hardly need to create a constructor, since
its job is automatically taken care of behind the scenes by the compiler.