0% found this document useful (0 votes)
33 views

C# Programming: 3.0 Fundamentals II

The document discusses C# programming fundamentals including garbage collection, exception handling, and the finally block. Garbage collection automatically reclaims memory from objects no longer being used. Exception handling uses try/catch blocks to gracefully handle errors. Finally blocks allow code to execute whether an exception was thrown or not after a try/catch.

Uploaded by

brianweldt
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

C# Programming: 3.0 Fundamentals II

The document discusses C# programming fundamentals including garbage collection, exception handling, and the finally block. Garbage collection automatically reclaims memory from objects no longer being used. Exception handling uses try/catch blocks to gracefully handle errors. Finally blocks allow code to execute whether an exception was thrown or not after a try/catch.

Uploaded by

brianweldt
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

C# Programming Purvis Samsoodeen

C# Programming
By Purvis Samsoodeen

3.0 Fundamentals II

3.4.0 Garbage Collection

Objects are dynamically allocated from a pool of free memory by using the new
operator. Of course, memory is not infinite, and the free memory can be
exhausted. Thus, it is possible for new to fail because there is insufficient free
memory to create the desired object.

C#’s garbage collection system reclaims objects automatically—occurring


transparently, behind the scenes, without any programmer intervention. It works
like this: When no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object is released. This recycled
memory can then be used for a subsequent allocation.

Garbage collection occurs only sporadically during the execution of your


program. It will not occur simply because one or more objects exist that are no
longer used. Thus, you can’t know precisely when garbage collection will take
place.

It is possible to define a method that will be called just prior to an object’s final
destruction by the garbage collector. This method is called a destructor, and it can
be used in some highly specialized situations to ensure that an object terminates
cleanly. For example, you might use a destructor to ensure that a system resource
owned by an object is released. It must be stated at the outset that destructors are a
very advanced feature that are applicable to certain specialized situations. They
are not normally needed.

Net Framework's garbage collection implicitly keeps track of the lifetime of the
objects that an application creates, but fails when it comes to the unmanaged
resources (i.e. a file, a window or a network connection) that objects encapsulate.
The unmanaged resources must be explicitly released once the application has
finished using them. .Net Framework provides the Object.Finalize method: a
method that the garbage collector must run on the object to clean up its
unmanaged resources, prior to reclaiming the memory used up by the object.

Page 1 of 7
C# Programming Purvis Samsoodeen

Since Finalize method does nothing, by default, this method must be overridden if
explicit cleanup is required.

3.5.0 Exception Handling

 Exception handling fundamentals

An exception is an error that occurs at runtime. Using C#’s exception-


handling subsystem, you can handle runtime errors in a structured and
controlled manner. A principal advantage of exception handling is that it
automates much of the error-handling code that would otherwise have been
entered “by hand” into any large program. For example, without the use of
exception handling, an error code would be returned by a method when it
fails, and this value must be checked manually each time the method is called.
This approach is both tedious and error-prone. Exception handling streamlines
error handling by allowing your program to define a block of code, called an
exception handler that is executed automatically when an error occurs. It is
not necessary to manually check the success or failure of each specific
operation or method call. If an error occurs, it will be processed by the
exception handler.
Another reason that exception handling is important is that C# defines
standard exceptions for common program errors, such as divide-by-zero or
index-out-of-range. To respond to these errors, your program must watch for
and handle these exceptions. In the final analysis, to be a successful C#
programmer means that you are fully capable of navigating C#’s exception-
handling subsystem.

 try and catch

At the core of exception handling are try and catch. These keywords work
together, and you can’t have a catch without a try. Here is the general form of
the try/catch exception-handling blocks:

try {
Page 2 of 7
C# Programming Purvis Samsoodeen

// block of code to monitor for errors


}
catch (ExcepType1 exOb) {
// handler for ExcepType1
}
catch (ExcepType2 exOb) {
// handler for ExcepType2
}

It is important to understand that all code within a try block is monitored for
exceptions.
When an exception is thrown, it is caught by its corresponding catch clause,
which then processes the exception. As the general form shows, there can be
more than one catch clause associated with a try. The type of the exception
determines which catch is executed. That is, if the exception type specified by
a catch matches that of the exception, then the block of code associated with
that catch clause is executed (and all other catch clauses are bypassed). When
an exception is caught, the exception variable exOb will receive its value.
If no exception is thrown, then a try block ends normally, and all of its catch
clauses are bypassed. Execution resumes with the first statement following the
last catch. Thus, a catch is executed only if an exception is thrown.

 Multiple catch clauses

You can associate more than one catch clause with a try. In fact, it is
common to do so. However, each catch must catch a different type of
exception.

Ref: Listing 6

 Nested try blocks

One try block can be nested within another. An exception generated within
the inner try block that is not caught by a catch associated with that try is
propagated to the outer try block.
Often, nested try blocks are used to allow different categories of errors to be
handled in different ways. Some types of errors are catastrophic and cannot be
fixed. Some are minor and can be handled immediately. Many programmers
use an outer try block to catch the most severe errors, allowing inner try
blocks to handle less serious ones. You can also use an outer try block as a
“catch all” block for those errors that are not handled by the inner block.
Page 3 of 7
C# Programming Purvis Samsoodeen

Ref: Listing 8

 Throw an exception

Ref: Listing 9

 The Exception class

Exception defines several properties. Three of the most interesting are


Message, StackTrace, and TargetSite. All are read-only. Message is a string
that describes the nature of the error. StackTrace is a string that contains the
stack of calls that lead to the exception. TargetSite returns an object that
specifies the method that generated the exception.
Exception also defines several methods. The one that you will most often use
is ToString( ), which returns a string that describes the exception.

Ref: Listing 12

 finally

Sometimes, you will want to define a block of code that will execute when a
try/catch block is left. For example, an exception might cause an error that
terminates the current method, causing its premature return. However, that
method may have opened a file or a network connection that needs to be
closed. Such types of circumstances are common in programming, and C#
provides a convenient way to handle them: finally.
To specify a block of code to execute when a try/catch block is exited,
include a finally block at the end of a try/catch sequence. The general form
of a try/catch that includes finally is shown here:

try {
// block of code to monitor for errors
}
Page 4 of 7
C# Programming Purvis Samsoodeen

catch (ExcepType1 exOb) {


// handler for ExcepType1
}
catch (ExcepType2 exOb) {
// handler for ExcepType2
}
// ...
finally {
// finally code
}
The finally block will be executed whenever execution leaves a try/catch
block, no matter what conditions cause it. That is, whether the try block ends
normally or because of an exception, the last code executed is that defined by
finally. The finally block is also executed if any code within the try block or
any of its catch clauses returns from the method.

Ref: Listing 11

 The built-in exceptions

Commonly used exceptions

3.6.0 Interfaces

Page 5 of 7
C# Programming Purvis Samsoodeen

 Interface fundamentals

In object-oriented programming, it is sometimes helpful to define what a class


must do, but not how it will do it.
Interfaces are syntactically similar to abstract classes. However, in an interface,
no method can include a body. That is, an interface provides no implementation
whatsoever. It specifies what must be done, but not how. Once an interface is
defined, any number of classes can implement it. Also, one class can implement
any number of interfaces.
When a class implements an interface, the class must implement the entire
interface. It cannot pick and choose which parts to implement.

 Add properties and indexers to interfaces

Like methods, properties are specified in an interface without any body. Here is
the general form of a property specification:
// interface property
type name {
get;
set;
}

Ref: Listing 12

An indexer declared in an interface has this general form:


// interface indexer
element-type this[int index] {
get;
set;
}

Ref: Listing 13

 Inherit interfaces

One interface can inherit another. The syntax is the same as for inheriting classes.
When a class implements an interface that inherits another interface, it must
Page 6 of 7
C# Programming Purvis Samsoodeen

provide implementations for all the members defined within the interface
inheritance chain.

Ref: Listing 14

 Structures

As you know, classes are reference types. This means that class objects are
accessed through a reference. This differs from the value types, which are
accessed directly. However, there can be times when it would be useful to be able
to access an object directly, in the way that value types are. One reason for this is
efficiency. Accessing class objects through a reference adds overhead onto every
access. It also consumes space. For very small objects, this extra space might be
significant. To address these concerns, C# offers the structure. A structure is
similar to a class, but is a value type, rather than a reference type.
Structures are declared using the keyword struct and are syntactically similar to
classes.
Here is the general form of a struct:
struct name : interfaces {
// member declarations
}
The name of the structure is specified by name.

 Enumerations

The keyword enum declares an enumerated type. The general form for an
enumeration is

enum name { enumeration list };

 Visual Studio support to create interfaces

Page 7 of 7

You might also like